gpt4 book ai didi

c# - 泛型方法继承 : VS and Xamarin Studio yield different results; which is right?

转载 作者:行者123 更新时间:2023-11-30 17:51:27 26 4
gpt4 key购买 nike

在继承层次结构中,我实现了以下通用方法:

public class Base
{
public virtual T Foo<T>()
{
Console.WriteLine("Base");
return default(T);
}
}

public class Derived : Base
{
public override T Foo<T>()
{
Console.WriteLine("Derived");
return default(T);
}
}

public class DerivedDerived : Derived
{
public override T Foo<T>()
{
base.Foo<string>();
return default(T);
}
}

这里的关键部分是,在 DerivedDerived 的方法实现中,我正在调用具有特定类型(string)的 base 类的方法>).

当我在 Visual Studio (2012) 或 LinqPad 中编译它并执行以下语句时:

var x = new DerivedDerived().Foo<string>();

输出是我直觉上期望的:

Derived

但是,如果我在 Xamarin Studio 4.0(Windows 或 Mac,在 Windows 上使用 .NET 或 Mono C# 编译和运行似乎无关紧要)中编译并运行相同的代码,输出为:

Base

这里的正确结果是什么?

C# 语言规范 5.0 的第 7.6.8 段包含以下声明:

When a base-access references a virtual function member (a method, property, or indexer), the determination of which function member to invoke at run-time (§7.5.4) is changed. The function member that is invoked is determined by finding the most derived implementation (§10.6.3) of the function member with respect to B (instead of with respect to the run-time type of this, as would be usual in a non-base access). Thus, within an override of a virtual function member, a base-access can be used to invoke the inherited implementation of the function member. If the function member referenced by a base-access is abstract, a binding-time error occurs.

乍一看,派生程度最高的实现(即 Derived.Foo)将从 DerivedDerived.Foo 调用,除非我以某种方式使继承短路通过在泛型方法调用中应用特定类型来实现层次结构?

最佳答案

正确的结果如下,从规范的写法就可以看出来。

Derived

编辑:规范说:

The function member that is invoked is determined by finding the most derived implementation (§10.6.3) of the function member with respect to B (instead of with respect to the run-time type of this, as would be usual in a non-base access).

DerivedDerived 的基类是Derived . Foo<T> 的最派生实现关于 DerivedDerived.Foo<T> .那是被调用的方法,而不是 Base.Foo<T> .

关于c# - 泛型方法继承 : VS and Xamarin Studio yield different results; which is right?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19449720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com