我试图理解,为什么我的方法的正确显式实现没有被调用。我有一个带有一个方法的基接口和一个子接口,它实现了基接口并覆盖了相同的方法(使用new关键字)。然后,我有一个只实现了子接口的类,两个方法都是显式实现的。
当我创建具有类型T(其中T是基接口)的泛型方法并用子接口调用此方法时,基接口的实现将被调用。我已经预料到,给定类型的方法将被调用(子接口)。你能帮我理解(或解释)为什么没有调用子接口的实现(参见输出,类型是子接口)?谢谢
请参阅以下代码从控制台输出:
IChild
基础测试
你好,世界!
interface IBase
{
void Test();
}
interface IChild : IBase
{
new void Test();
}
class Test : IChild
{
void IBase.Test()
{
Console.WriteLine("Base test");
}
void IChild.Test()
{
Console.WriteLine("Child Test");
}
}
class Program
{
static void Main(string[] args)
{
TestMethod<IChild>(new Test());
Console.WriteLine("Hello World!");
}
static void TestMethod<T>(T test) where T : IBase
{
Console.WriteLine(typeof(T).Name);
test.Test();
}
}发布于 2021-04-22 17:49:30
首先要理解的是,IBase.test和IChild.Test实际上是两个完全不相关的不同方法,只是名称相同而已。事实上,如果您查看generated IL,您将看到一个方法被引用为IBase::Test或IBase.Test,另一个被引用为IChild::Test或IChild.Test -这两个不同的方法使用了完全不同的名称。
您将TestMethod<T>限制为IBase,因此此方法根本不了解IChild。因此,当您调用T.Test()时,编译器将生成对IBase::Test()的调用,该调用将完全忽略不相关的方法IChild::Test()。
.method private hidebysig static
void TestMethod<(IBase) T> (
!!T test
) cil managed
{
// Method begins at RVA 0x2086
// Code size 34 (0x22)
.maxstack 8
IL_0000: ldtoken !!T
IL_0005: call class [System.Private.CoreLib]System.Type [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle)
IL_000a: callvirt instance string [System.Private.CoreLib]System.Reflection.MemberInfo::get_Name()
IL_000f: call void [System.Console]System.Console::WriteLine(string)
IL_0014: ldarga.s test
IL_0016: constrained. !!T
IL_001c: callvirt instance void IBase::Test()
IL_0021: ret
} // end of method Program::TestMethodhttps://stackoverflow.com/questions/67210550
复制相似问题