gpt4 book ai didi

c# - 为什么编译器在传递继承类型时会给出不明确的调用错误?

转载 作者:行者123 更新时间:2023-12-02 04:47:07 25 4
gpt4 key购买 nike

C# 编译器中发生了什么导致以下歧义调用编译错误?

同样的问题适用于扩展方法,或者当 TestClass 是通用的并且使用实例而不是静态方法时。

我意识到这很容易解决(例如,在方法调用时将 secondInstance 转换为 Test1)但我更好奇编译器正在应用什么逻辑用于方法选择。

我的假设是编译器在方法检测上应用某种程度的特异性度量(如 CSS)以确定最具体的匹配 - 这是否无效?

class Type1 { }
class Type2 : Type1 {}

class TestClass
{
public static void Do<T>(T something, object o) where T : Type1
{}

public static void Do(Type1 something, string o)
{}
}

void Main()
{
var firstInstance = new Type1();
TestClass.Do(firstInstance, new object()); // Calls Do<T>(T, obj)
TestClass.Do(firstInstance, "Test"); // Calls Do(Type1, string)

var secondInstance = new Type2();
TestClass.Do(secondInstance, new object()); // Calls Do<T>(T, obj)
TestClass.Do(secondInstance, "Test"); // "The call is ambiguous" compile error
}

//编辑:mike z 提出了一个概念,我将其解释为“转换距离”被用作方法选择的权重。对此的测试似乎支持这一点(尽管我不确定 Type->Generic Type 是如何加权的)。

// Add the following two methods to TestClass
public static void Do<T>(T something) where T : Type1
{}

public static void Do(Type1 something)
{}

public static void Do<T>(T something, object o) where T : Type1
{}

public static void Do(Type1 something, string o)
{}

void Main()
{
var firstInstance = new Type1();

// Can't select string
TestClass.Do(firstInstance, new object()); // Calls Do<T>(T, obj)

// Do() distance is 0, Do<T> distance is 1
TestClass.Do(firstInstance, "Test"); // Calls Do(Type1, string)

// Do() distance is 0, Do<T> distance is ? (but more than 0?)
TestClass.Do(firstInstance); // Calls Do(Type1)

var secondInstance = new Type2();

// Can't select string
TestClass.Do(secondInstance, new object()); // Calls Do<T>(T, obj)

// Do() distance is 1, Do<T> distance is 1
TestClass.Do(secondInstance, "Test"); // "The call is ambiguous" compile error

// Do() distance is 1, Do<T> distance is ? (but less than 1?)
TestClass.Do(secondInstance); // Calls Do<T>(T)

}

最佳答案

过载决议在第 7.5.3 节中介绍。它很复杂,但基本思想是编译器将根据它需要执行的转换的数量和类型来确定“最佳”重载。

对于情况 1,泛型重载有一个精确的类型匹配。
对于情况 2,非泛型重载存在精确类型匹配。
对于情况 3,泛型重载是完全匹配。注意:您的评论不正确。 T 的类型将为 Type2
对于情况 4,泛型重载需要从字符串到对象的转换,而非泛型方法需要从 Type2Type1 的转换。请注意,这些都是对基本类型的引用转换。由于在这两种情况下都需要一种相同类型的转换,因此编译器拒绝为您做出决定,并给您一个调用不明确的错误。没有“最佳”匹配。

关于c# - 为什么编译器在传递继承类型时会给出不明确的调用错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19580769/

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