I have a control that overrides 开发者_高级运维the protected GetService method and assigns it to the IServiceProvider interface:
Class MyControl
Inherits Control
Implements IServiceProvider
Protected Overrides Sub GetService(t as Type) as Object Implements IServiceProvider.GetService
End Sub
End Class
I'm struggling to convert this to c#. I've tried implicit v. explicit but I must be getting the syntax wrong.
You would do this like:
class MyControl : Control, IServiceProvider
{
// Explicitly implement this
object IServiceProvider.GetService(Type t)
{
// Call through to the protected version
return this.GetService(t);
}
// Override the protected version...
protected override object GetService(Type t)
{
}
}
That being said, Control already implements IServiceProvider (via Component). You really can just do:
class MyControl : Control
{
protected override object GetService(Type t)
{
}
}
There is a bit of a corner issue with VB.Net interface implementation that needs to be considered when porting to C#. A implemented interface method in VB.Net essentially uses both implicit and explicit interface implementations in the same line. This allows for cases like mismatched names and non-public implementations.
For example the following is also a legal implementation of IServiceProvider
Class Example
Implements IServiceProvider
Private Sub GetServiceWrongName(t As Type) As Object Implements IServiceProvider.GetService
...
End Sub
End Class
It translates to roughly the following C# code
class Example : IServiceProvider {
public object GetServiceWrongName(t as Type) {
..
}
object IServiceProvider.GetService(t as Type) {
return GetServiceWrongName(t);
}
}
The original VB.NET method is protected, so I guess it's the equivalent of explicit interface implementation in C#:
class MyControl : Control, IServiceProvider
{
object IServiceProvider.GetService(Type t)
{
...
}
}
精彩评论