In C#, is it possible to implement an interface member using a member with a different name, like you can do in VB.NET?

混江龙づ霸主 提交于 2020-01-12 13:47:09

问题


Ok, this is a question I'm asking, not as in demonstrating good coding practices (this actually could be considered a bad practice) but rather in regards to 'can' it be done at all.

That said, in VB.NET you implement an interface like this...

Sub SomeInterfaceMember()
    Implements ISomeInterface.SomeInterfaceMember
End Sub

while in C# you do it explicitly like this (which can only be called via the interface)...

void ISomeInterface.SomeInterfaceMember(){}

or more simply, implicitly like this (in which case you can call it directly, or via the interface)...

void SomeInterfaceMember(){} // <-- This name matches the interface member

However, regarding VB, you can also do this, using any name you want for the member...

Sub SomeRandomMemberName() // <-- This name doesn't match the interface member
    Implements ISomeInterface.SomeInterfaceMember
End Sub

In other words, the method that handles the implementation can have a completely different name than the interface's member name.

I'm just wondering if there's something similar to this in C#. (Yes, I know I can simply do an explicit interface, then access it via another 'wrapper' member with a different name that simply delegates to it, but in VB.NET, you do both with a single method.)

So can that be done?

Mark


回答1:


No, this isn't possible in C#. (You can't "explicitly implement an interface" in VB.NET either.)




回答2:


It "can" be done in the sense that you can achieve a result that's basically indistinguishable from the VB scenario by using explicit implementation + a public method that calls that implementation.

Aside from cases involving reflection, this really will end up being the same thing.



来源:https://stackoverflow.com/questions/5533659/in-c-is-it-possible-to-implement-an-interface-member-using-a-member-with-a-dif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!