【发布时间】:2020-10-10 22:29:30
【问题描述】:
在下面的代码中,我(显然是错误地)期望绑定/调用更具体(如果您愿意,可以派生)类型的方法:
using System;
public class Program
{
public static int integer = 52;
public static Program program = new Program();
public static void Main()
{
TestReturn(program); // this works as expected all the way
TestReturn(integer); // 1. this not quite...
}
public static T TestReturn<T>(T t) // 2. TestReturn<Int32> all good...
{
Console.WriteLine("In TestReturn<" + typeof(T) + ">");
return (T)Extensions.Undefined(t); // 3. wrong call
}
}
public static class Extensions
{
public static object Undefined(this object t) // 4. this is called, instead of (5)
{
Console.WriteLine("In Undefined(obj)");
return null;
}
public static int Undefined(this int b) // 5. this is expected to be called
{
Console.WriteLine("In Undefined(int)");
return int.MinValue;
}
}
输出:
In TestReturn<Program>
In Undefined(obj)
In TestReturn<System.Int32>
In Undefined(obj)
Run-time exception (line 17): Object reference not set to an instance of an object.
有人能说出为什么会发生这种情况以及如何做到这一点才能按我的预期工作吗?
【问题讨论】:
-
由于您对泛型类型没有任何限制,因此编译器必须选择一种适用于所有可能
T的方法 -
我想值得指出的是,如果 C# 是一种解释型语言,它可能会按预期工作,但正如 UnholySheep 指出的那样,在编译时编译器需要选择应该由 @ 调用的扩展方法987654325@,没有
where子句将默认为最通用的。 -
dotnetfiddle.net/UojDTv 会将调用哪个方法的决定推迟到运行时。这似乎是您想要的。
-
这是我的收获:编译器在编译时无法解析
T。即使代码具有具体类型的调用。它最多只能对T做出一个大致的了解:是否T可以根据约束从任何调用的类型中分配。
标签: c# generics extension-methods