gpt4 book ai didi

c# - 重载解析选择不兼容的泛型方法而不是兼容的基类方法

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

我遇到了一个我没想到的重载解析问题。显然,编译器宁愿解析对 MyPrint 的调用。方法传递 "Hello world"MyPrint<T>(T : struct)在派生类中比 MyPrint(string)在基类中定义。由于解析器选择的方法不接受该字符串,因此出现编译错误。

我想这与 Brittle Base Class 问题有关 Jon Skeet wrote in his book , 和 Eric Lippert on his blog . Lippert 引用该标准的话说:

Methods in a base class are not candidates if any method in a derived class is applicable.

但我没有看到派生类中的任何方法适用,而且从错误判断编译器也不适用。我想知道两件事:为什么它会这样工作,以及如何让 C# 再次执行我希望它执行的操作?

证明问题的人为示例:

class Program
{
static void Main(string[] args)
{
Derived d = new Derived();

d.MyPrint(10);

// ERROR: The type 'string' must be a non-nullable value type
// in order to use it as parameter 'T'
// in the generic type or method 'Derived.MyPrint<T>(T)'.
d.MyPrint("Hello world!");
}
}

class Base
{
// I print only strings.
public void MyPrint(string value)
{
Console.WriteLine("String: " + value);
}
}

class Derived : Base
{
// I print any primitive type, enums and DateTime,
// but NOT string (since that is not a value type).
public void MyPrint<T>(T value)
where T : struct, IConvertible
{
Console.WriteLine("IConvertible: " + value.ToString());
}
}

最佳答案

你已经找到了一半的原因,但你还需要Constraints are not part of the signature.结合“如果派生类中的任何方法适用,则基类中的方法不是候选者”,您会发现在重载解析期间有两种方法看起来像 MyPrint(string) 因此适用, 因此选择最派生类中的那个。只有在那之后才会检查约束,然后检查失败。

关于c# - 重载解析选择不兼容的泛型方法而不是兼容的基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8458836/

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