如果我有这个:
class Pair<T> {}
class Animal {}
class Human {}然后:
Pair<Animal> a = new Pair<Animal>();
Pair<Human> h = new Pair<Human>();我读到CLR只创建了一次专门版本的Pair,其中T被object所取代。在创建h之后,它将重用该版本。
但我不明白这意味着什么。当object是Animal类型和Human类型时,它如何以一种类型安全的方式知道?
“重用”这个词是什么意思?
发布于 2016-03-11 16:54:14
不--这就是Java所做的--它在编译时检查是否使用了正确的类型,但是在幕后,一切都只是一个Pair<object>。
C#要好得多,因为它每次都会创建一个真正的新类型。为什么这种方法更好呢?因为您可以在运行时使用反射(在Java中不能做的事情)找到类型。
如果生成IL,您可以看到这一点--您可以看到唯一的类型:
IL_0000: nop
IL_0001: newobj UserQuery<UserQuery+Animal>+Pair`1..ctor
IL_0006: stloc.0 // a
IL_0007: newobj UserQuery<UserQuery+Human>+Pair`1..ctor
IL_000C: stloc.1 // h
IL_000D: ret
Pair`1..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ret
Animal..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ret
Human..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ret 发布于 2016-03-11 17:23:01
它如何以一种类型安全的方式知道什么时候对象是动物类型,什么时候是人类类型?
您不能,至少不能在Pair类中这样做。现在,在基于类型声明的Pair类之外:
class Pair<T> {
public T Value {get; set;} // the compiler has no idea what the type of `T` is at compile-time
}
Pair<Animal> a = new Pair<Animal>();
a.Value = new Animal(); // here the compiler knows that `Value` is an `Animal` based on the declared type of `a`.https://stackoverflow.com/questions/35945684
复制相似问题