[英]Are typeof(T) and this.GetType().GetGenericArguments()[0] always equivalent within a generic class instance?
我有一个包装另一个协变安全的泛型类。 我想让在运行时获取实例的派生最多的类型变得简单:
public interface IReference<out T> { Type UnderlyingType { get; } }
public class Reference<T> : IReference<T> where T : class
{
public Type UnderlyingType => /*typeof(T)*/ this.GetType().GetGenericArguments()[0];
}
我很确定在上面的例子中我可以使用typeof(T)
来使上面的实现更快 - 但我想确保这不会导致编译时类型返回的情况与什么不同运行时类型可能是。
例如,如果有人去:
IReference<object> weak = new Reference<string>()
IdentifyReference(weak);
void IdentifyReference<T>(IReference<T> unknown) where T : class {
Print(typeof(T));
Print(unknown.UnderlyingType);
}
我想要以下输出:
object
string
由于多态的工作方式,您可以确定UnderlyingType
属性中的typeof(T)
生成运行时类型。
编译器在编译时根本没有足够的信息来确定unknown.UnderlyingType
是什么。 请记住, IReference
是一个接口,因此编译器对unknown
具体类型unknown
。 因此,它甚至不知道应该执行这个特定的实现:
public Type UnderlyingType => typeof(T) /*this.GetType().GetGenericArguments()[0]*/;
就编译器而言,它可能是Foo
的实现,恰好实现了IReference<object>
。
因此,表达式typeof(T)
在运行时计算,当运行时多态性(动态分派选择正确的实现)发生时。 多态的工作方式导致表达式始终在运行时类型的上下文中进行计算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.