Function overloads using interfaces and explicit implementations
I have the following interface:
public interface Iface
{
void Sample1();
void Sample1(bool value);
}
And the implementation is shown below. Note: It is requried that Sample1's implementation be explicit (due to generic constraints voodoo)
public class myCLass : Iface
{
void Iface.Sample1()
{
this.Sample1(true);
}
void Iface.Sample1(bool value)
{
}
}
Trying to call the overload, however, results in this error:
Error 5 'myCLass' does not contain a definition for 'Sample1' and no extension method 'Sample开发者_如何学Go1' accepting a first argument of type 'myCLass' could be found (are you missing a using directive or an assembly reference?) Q:\common\VisualStudio\Charting\Drilldowns.cs 18 15 Charting
Bottom line: I think I'm unsure of the syntax I should be using to call the 'other' overload in the same interface.
Since you're implementing the interface explicitly, you need to cast yourself to the interface:
((IDrilldown)this).Sample1(true);
Or, if you don't like the in-line cast:
IDrilldown idd = (IDrilldown)this;
idd.Sample1(true);
If you did a normal, implicit implementation, you'd be able to call the method directly. Explicit interface implementations are only usable on a variable specifically defined as that interface.
Explicit interface implementations aren't public methods.
You can only call them by casting to the interface:
((IDrilldown)this).Sample1(true);
I think your code is messed up from renaming, or else has some code in it that wasn't included in the question (DFResults, IDrilldown). I'm going to assume DFResults was supposed to be MyClass and IDrilldown was supposed to be Iface.
So you have an interface IFace, which declares 2 methods. You have a class that implements the interface, and EXPLICITLY implements that interface. You seem to accept that it must be explicit, but with that, you cannot call the method through the class, only by casting to the interface.
public interface IFace
{
void SampleFunc();
}
public class MyClass : IFace
{
void IFace.SampleFunc();
}
public static void Program()
{
MyClass instance = new MyClass();
instance.SampleFunc(); //Illegal
((IFace)instance).SampleFunc(); Legal
}
精彩评论