在几个不同的场合,我试图从一个变量中提取声明的类型,距离它的声明相对较远,结果发现 typeof(T)
只适用于类型名称。
我想知道是否会有任何重大更改也允许 typeof(variable)
。
例如,使用此代码:
class Animal { /* ... */ }
class Goat : Animal { /* ... */ }
/* ... */
var g = new Goat();
Animal a = g;
Console.WriteLine(typeof(Goat));
Console.WriteLine(typeof(Animal));
Console.WriteLine(g.GetType());
Console.WriteLine(a.GetType());
你会得到类似的东西:
Goat
Animal
Goat
Goat
为什么不能这样做:
Console.WriteLine(typeof(g));
Console.WriteLine(typeof(a));
Goat
Animal
我粗略地浏览了一下规范,没有发现任何冲突。我认为它会澄清“为什么是这种类型?”的问题。使用 typeof
运算符时。
我知道编译器是有能力的,在这里。使用扩展方法的实现实际上是微不足道的:
public static Type TypeOf<T>(this T variable)
{
return typeof(T);
}
但这感觉很脏,滥用了编译器的类型推断。
最佳答案
我认为这里的问题是 .GetType() 比 typeof() 旧。在 C# 中曾经有一天你需要做的事情
"0".GetType()
为了得到String类型(例如),直到typeof()诞生。我认为如果这个概念是原始语言设计的一部分,那么它确实可以像您描述的那样工作。由于 typeof() 是该语言的较晚介绍,因此设计人员必须做出选择:过时/弃用/删除 .GetType() (并在此过程中使它的许多许多用途过时),使 typeof()在功能上与 GetType() 重叠(这就是您要问的),或者使 typeof() 的用法不与 GetType() 重叠。我认为 C# 的人只是选择不让功能重叠(为了让事情简单明了),所以 typeof() 像今天这样受到限制。
关于C#/.NET : Is `typeof(variable)` a possible language feature?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4125322/