Runtime: 通用接口方法未调用

创建于 2018-08-10  ·  3评论  ·  资料来源: dotnet/runtime

在.NET 2/3/4 / 4.5 / 4.6.1和.Net Core 2.1行为上经过测试的示例代码对于所有行为都是相同的,为什么要这样处理?

显然,对PrintIt<T>的调用正在创建正确的类型Bar但从未实际调用正确的方法。

样例代码:

interface PrintMe
{
    void Print();
}

class Foo : PrintMe
{
    public void Print()
    {
        Console.WriteLine("Foo!");
    }
}

class Bar : Foo
{
    public new void Print()
    {
        Console.WriteLine("Bar!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        PrintIt<Foo>();
        PrintIt<Bar>();

        var foo = new Foo();
        var bar = new Bar();

        foo.Print();
        bar.Print();

        Console.ReadKey();
    }

    static void PrintIt<T>() where T : PrintMe, new()
    {
        new T().Print();
    }
}

输出:

Foo!
Foo!
Foo!
Bar!

预期产量:

Foo!
Bar!
Foo!
Bar!
question tracking-external-issue

最有用的评论

当您“新建” Print()时,该方法不属于PrintMe界面。

您将获得与相同的结果

((PrintMe)new Bar()).Print();

完全没有泛型。

所有3条评论

当您“新建” Print()时,该方法不属于PrintMe界面。

您将获得与相同的结果

((PrintMe)new Bar()).Print();

完全没有泛型。

这不是CLR做什么的问题,而是有关语言做什么的问题。 C#规范说

一个类继承其基类提供的所有接口实现。

如果没有显式重新实现接口,则派生类无法以任何方式更改其从其基类继承的接口映射。

然后,该规范提供了一个与上述示例几乎相同的示例。

这也意味着要使其表现出所需的行为,您需要重新实现该接口:

c# class Bar : Foo, PrintMe { public new void Print() { Console.WriteLine("Bar!"); } }

@svick感谢您的回答

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

nalywa picture nalywa  ·  3评论

matty-hall picture matty-hall  ·  3评论

iCodeWebApps picture iCodeWebApps  ·  3评论

Timovzl picture Timovzl  ·  3评论

jamesqo picture jamesqo  ·  3评论