首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >泛型的低级实现

泛型的低级实现
EN

Stack Overflow用户
提问于 2016-03-11 16:50:14
回答 2查看 85关注 0票数 2

如果我有这个:

代码语言:javascript
复制
class Pair<T> {}

class Animal {}
class Human {}

然后:

代码语言:javascript
复制
Pair<Animal> a = new Pair<Animal>();
Pair<Human> h = new Pair<Human>();

我读到CLR只创建了一次专门版本的Pair,其中Tobject所取代。在创建h之后,它将重用该版本。

但我不明白这意味着什么。当objectAnimal类型和Human类型时,它如何以一种类型安全的方式知道?

重用”这个词是什么意思?

EN

回答 2

Stack Overflow用户

发布于 2016-03-11 16:54:14

不--这就是Java所做的--它在编译时检查是否使用了正确的类型,但是在幕后,一切都只是一个Pair<object>

C#要好得多,因为它每次都会创建一个真正的新类型。为什么这种方法更好呢?因为您可以在运行时使用反射(在Java中不能做的事情)找到类型。

如果生成IL,您可以看到这一点--您可以看到唯一的类型:

代码语言:javascript
复制
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         
票数 1
EN

Stack Overflow用户

发布于 2016-03-11 17:23:01

它如何以一种类型安全的方式知道什么时候对象是动物类型,什么时候是人类类型?

您不能,至少不能在Pair类中这样做。现在,在基于类型声明的Pair类之外:

代码语言:javascript
复制
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`.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35945684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档