Which interface will be implemented?
I have a question regarding Interface. There are 2 interface both contain the same Method Test(). Now I'm inheriting both the interface in Sample class.I want to know which Interface's method will be called? My code sample is below:
interface IA
{
void Test();
}
interface IB
{
void Test();
}
class Sample: IA, IB
{
public void Test()
{
Console.WriteLine("Which interface will开发者_Go百科 be implemented IA or IB???!");
}
}
class Program
{
public static void Main(string[] args)
{
Sample t = new Sample();
t.Test();//Which Interface's Method will called.
Console.ReadLine();
}
}
Thanks Vijendra Singh
The result will be the same for both. If you want different behaviour per interface, you have to explicitly implement them:
interface IA
{
void Test();
}
interface IB
{
void Test();
}
class Sample: IA, IB
{
void IA.Test()
{
Console.WriteLine("Hi from IA");
}
void IB.Test()
{
Console.WriteLine("Hi from IB");
}
public void Test() //default implementation
{
Console.WriteLine("Hi from Sample");
}
}
class Program
{
public static void Main(string[] args)
{
Sample t = new Sample();
t.Test(); // "Hi from Sample"
((IA)t).Test(); // "Hi from IA"
((IB)t).Test(); // "Hi from IB"
Console.ReadLine();
}
}
If you want default behaviour, create a method with the same signature (thus an implicit interface implementation) and add code for that case. Usually, you just want the explicit implementation though.
Both.
If you have the code
IA a = new Sample();
or
IB b = new Sample();
the output is the same.
EDIT
What interface is called?
Both are implemented None is called.
Interfaces exist to make the programmer awere of what method (what interface) the class as.
You need to use a concrete implementation of the interface. The methods form the concrete class are the methods that are called.
You're thinking of an interface the wrong way. An interface isn't an implementation, it's an abstraction.
In telling the compiler that Sample is both IA and IB, you have simply said that it can be cast to either of these types and has all of the functionality required to do whatever the calling code expects it to be able to do.
ie. in the following code
Sample sample = new Sample();
sample.Test();
IA a = sample;
a.Test();
IB b = sample;
b.Test();
It is not calling three separate methods called Test, it is calling the Test method from Sample each time. This is as opposed to
object obj = sample;
obj.Test();
which would fail to compile even though obj has a method Test by nature of being type Sample.
This is particularly powerful when you're looking at passing an object as an argument to another method.
public void DoTest(IA a)
{
a.Test();
}
Sample sample = new Sample();
DoTest(sample);
In this case, the compiler only knows that anything with a contract of IA has a Test method. It doesn't care what Type it is, that's the business of the calling code.
You're directly calling Sample.Test() method, since the "t" variable is declared as "Sample t"
精彩评论