在.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!
这不是CLR做什么的问题,而是有关语言做什么的问题。 C#规范说:
一个类继承其基类提供的所有接口实现。
如果没有显式重新实现接口,则派生类无法以任何方式更改其从其基类继承的接口映射。
然后,该规范提供了一个与上述示例几乎相同的示例。
这也意味着要使其表现出所需的行为,您需要重新实现该接口:
c#
class Bar : Foo, PrintMe
{
public new void Print()
{
Console.WriteLine("Bar!");
}
}
@svick感谢您的回答
最有用的评论
当您“新建” Print()时,该方法不属于PrintMe界面。
您将获得与相同的结果
完全没有泛型。