如何调用自己类中的接口方法?
我的 MySqlConnection 类实现 IDatabaseConnection 接口。在 update 方法中,我想调用 connect()
但找不到这个方法,我该如何调用它?
class MySqlConnection : IDatabaseConnection
{
void IDatabaseConnection.connect()
{
...
}
void IDatabaseConnection.update()
{
connect(); // here
...
}
}
My MySqlConnection class implements IDatabaseConnection
interface. In update method, I want to call connect()
but it cannot find this method, How can I call it?
class MySqlConnection : IDatabaseConnection
{
void IDatabaseConnection.connect()
{
...
}
void IDatabaseConnection.update()
{
connect(); // here
...
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
显然您正在使用显式接口实现,但您的语法不正确(您不能在其上指定访问修饰符)。
要调用该方法,只需将
this
转换为IDatabaseConnection
:Apparently you're using explicit interface implementation, except your syntax is incorrect (you mustn't specify an access modifier on it).
To call the method, just cast
this
toIDatabaseConnection
:您可以使用:
原因是您正在显式实现此接口,因此您只能在转换后调用这些方法。为什么要显式实现它并使这些方法
私有
?我认为,连接类具有public
connect
和update
方法更常见。You can use:
The reason is that you are implementing this interface explicitly, so you can only call these methods after a conversion. Why do you implement it explicitly and make these methods
private
? It's more common that a connection class haspublic
connect
andupdate
methods, I think.显式接口实现:
相当好 - 隐式接口实现:
Explicit interface implementation:
Rather better - implicit interface implementation:
这里似乎有几个问题——您的 MySqlConnection 没有实现 IDatabase 接口,但您在该接口中显式实现了一个方法?
这可能会有所帮助——我可能误解了你想要实现的目标。
http://msdn.microsoft.com/en-us/库/aa288461(VS.71).aspx
There seems to be a couple of problems here -- your MySqlConnection doesn't implement the IDatabase interface, but you're explicitly implementing a method in that interface?
This might help -- I may have misunderstood what you're trying to achieve.
http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx
这就是所谓的显式接口实现。但是,如果您像这样编写类,它会正常工作:
请注意,这些方法是作为公共方法实现的。
显式实现使得它们在任何地方都无法访问,甚至在类本身内部也是如此。这就是为什么在声明它们时不能使用
private
关键字。但是,仍然可以通过该界面“公开”访问它们。如果出于某种充分的原因您确实想使用显式实现,您可以转换为接口并从那里调用:That is called explicit interface implementation. But if you write your class like this it works normally:
Notice that the methods are implemented as public methods.
Explicit implementation makes them inaccessible everywhere, even inside the class itself. That's why you can't use the
private
keyword when declaring them. They can still be accessed "publicly" through the interface, however. If for some good reason you really want to use explicit implementations you can cast to the interface and call from there: