如果您在接口I1和I2 TheMethod()
,和下面的类当你用相同的方法实现两个接口时,你怎么知道哪一个被调用?
class TheClass : I1, I2
{
void TheMethod()
}
如果事情实例TheClass
,它如何知道它正在使用的界面?
如果您在接口I1和I2 TheMethod()
,和下面的类当你用相同的方法实现两个接口时,你怎么知道哪一个被调用?
class TheClass : I1, I2
{
void TheMethod()
}
如果事情实例TheClass
,它如何知道它正在使用的界面?
如果这就是客户端代码使用该类的方式,那并不重要。如果它需要做一些特定于接口的事情,它应该声明它所需要的接口,并将该类分配给该接口。
I1 i = new TheClass()
i.TheMethod();
当然,使用当前的实现TheClass
,这并不重要,如果声明i
为I1
,或I2
,因为你只需要一个单一的实现。
如果你想每个接口都有一个单独的实现,那么你需要创建明确的实现......
void I1.TheMethod()
{
Console.WriteLine("I1");
}
void I2.TheMethod()
{
Console.WriteLine("I2");
}
但请记住,明确的实现不能公开。您可以明确地实现一个,并将另一个作为可以公开的默认值。
void I1.TheMethod()
{
Console.WriteLine("I1");
}
public void TheMethod()
{
Console.WriteLine("Default");
}
查看详情,请点击the msdn article。
我看看msdn。它现在有点合理。我不认为我需要明确的实现。只有一个就足够了。 – user758055 2011-05-17 22:17:10
只要方法签名相同,对于实现两个或多个接口方法的方法来说,这是完全合法的。
没有办法知道“通过哪个接口”调用某个方法 - 没有这样的概念(也没关系)。
您不用调用它的接口。一个接口只是一个定义你可以调用哪些方法的契约。你总是调用实现。
真正的问题是,“谁在乎它使用的是哪个接口?”真的,它不是“使用”界面。它使用实现来实现接口。
如果两种方法都是公共的,那么无论调用哪个接口,都会调用同一个方法。如果您需要更多的粒度,则需要使用显式接口实现:
class TheClass : I1, I2
{
void I1.TheMethod() {}
void I2.TheMethod() {}
}
使用可能看起来像:
TheClass theClass = new TheClass();
I1 i1 = theClass;
I2 i2 = theClass;
i1.TheMethod(); // (calls the first one)
i2.TheMethod(); // (calls the other one)
有一点要记住的是,如果你让都实现明确的,您将不再能够调用TheMethod
在声明为TheClass
变量:
theClass.TheMethod(); // This would fail since the method can only be called on the interface
当然,如果你愿意,你可以明确地只实现其中一个实现,并保持另一个公开,在这种情况下调用TheClass
将调用公共版本。
这是无关紧要的。投射到任何接口都会导致被调用的方法,但由于接口不能包含代码,因此不能从中继承行为。
如果您实例化类,那么您没有使用任何接口。如果您将引用强制转换为任一接口,那么您正在使用该接口。例如:
TheClass c = new TheClass();
c.TheMethod(); // using the class
I1 i = new TheClass();
i.TheMethod(); // using the I1 interface
当您的类声明时,两个接口都将使用相同的方法。如果仅指定接口的方法
class TheClass : I1, I2
{
void TheMethod() {} // used by the class
void I1.TheMethod() {} // used by the I1 interface
void I2.TheMethod() {} // used by the I2 interface
}
,除非你投的参考接口首先你无法到达的方法:你也可以指定类和方法的不同接口
class TheClass : I1, I2
{
void I1.TheMethod() {} // used by the I1 interface
void I2.TheMethod() {} // used by the I2 interface
}
如果指定只某些接口不同的方法,其他的接口将使用相同的实现作为类:
class TheClass : I1, I2
{
void TheMethod() {} // used by the class and the I1 interface
void I2.TheMethod() {} // used by the I2 interface
}
public interface IA
{
void Sum();
}
public interface IB
{
void Sum();
}
public class SumC : IA, IB
{
void IA.Sum()
{
Console.WriteLine("IA");
}
void IB.Sum()
{
Console.WriteLine("IB");
}
public void Sum()
{
Console.WriteLine("Default");
}
}
public class MainClass
{
static void Main()
{
IA objIA = new SumC();
IB objIB = new SumC();
SumC objC = new SumC();
objIA.Sum();
objIB.Sum();
objC.Sum();
Console.ReadLine();
}
}
显式实现不能公开..您需要将Default方法设置为public .. – 2016-05-30 06:37:21
如果你在接口中只有'TheMethod()',那么我猜你希望实现是公开的。 – musaul 2011-05-17 21:07:09