首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在泛型和继承中调用了不正确的显式方法

问在泛型和继承中调用了不正确的显式方法
EN

Stack Overflow用户
提问于 2021-04-22 17:28:04
回答 1查看 49关注 0票数 0

我试图理解,为什么我的方法的正确显式实现没有被调用。我有一个带有一个方法的基接口和一个子接口,它实现了基接口并覆盖了相同的方法(使用new关键字)。然后,我有一个只实现了子接口的类,两个方法都是显式实现的。

当我创建具有类型T(其中T是基接口)的泛型方法并用子接口调用此方法时,基接口的实现将被调用。我已经预料到,给定类型的方法将被调用(子接口)。你能帮我理解(或解释)为什么没有调用子接口的实现(参见输出,类型是子接口)?谢谢

请参阅以下代码从控制台输出:

IChild

基础测试

你好,世界!

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

发布于 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()。

代码语言:javascript
复制
    .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::TestMethod
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67210550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档