If we have a class that inherits from multiple interfaces, and the interfaces have methods with the same name, how can we implement these methods in my class? How we can specify that which method of which interface is implemented?
+2
A:
You can implement one or both of those interfaces explicitly.
Say that you have these interfaces:
public interface IFoo1
{
void DoStuff();
}
public interface IFoo2
{
void DoStuff();
}
You can implement both like this:
public class Foo : IFoo1, IFoo2
{
public void IFoo1.DoStuff() { }
public void IFoo2.DoStuff() { }
}
Mark Seemann
2010-03-03 12:32:34
+7
A:
By implementing the interface explicitly, like this:
public interface ITest {
void Test();
}
public interface ITest2 {
void Test();
}
public class Dual : ITest, ITest2
{
void ITest.Test() {
Console.WriteLine("ITest.Test");
}
void ITest2.Test() {
Console.WriteLine("ITest2.Test");
}
}
Note that the functions are private on the class, so you have to assign an object of that class to a variable defined as that particular interface:
var dual = new Dual();
ITest test = dual;
test.Test();
ITest2 test2 = dual;
test2.Test();
Pete
2010-03-03 12:34:20
A:
Sometimes you may even need to do:
public class Foo : IFoo1, IFoo2
{
public void IFoo1.DoStuff() { }
public void IFoo2.DoStuff()
{
((IFoo1)this).DoStuff();
}
}
Sebastian
2010-04-24 17:17:19