我搜索了C# 中的泛型类型
,我得出了这个结论:
- 所有引用类型都基于
Class
- 所有值类型都基于
struct
结构和类之间的主要区别,除了值和引用类型之间的全局区别外,还有:
struct中没有继承
结构不能包含空构造函数(不带参数)
- 通用类型有六个基本实现:
Where T: class ==>the generic parameter must be a reference type
Where T:classA ==>the generic parameter must be an instance of the class classA
Where T:InterfaceA ==> the generic parameter must implement the interface InterfaceA
Where T:New() ==> the generic parameter must be a class + have a default empty constructor
Where T:U ==> the generic parameter must be derived the class U or implement the interface U
Where T: struct ==> the generic parameter must be a value type
所以我需要知道:
- 我的结论是否正确?
- 我不明白 : 之间的区别
where T: New() ==> class with empty constructor
where T: class, New() ==> class with empty constructor
为什么使用第二种形式?为什么我们不只使用第一个?
谢谢,
最佳答案
您所描述的是通用约束。
Where T:New() ==> the generic parameter must be a class + have a default empty constructor
不,那只是说“类型参数必须有一个无参数的构造函数”。这实际上包括所有 值类型。即使您无法在 C# 6 之前为结构声明自己的无参数构造函数,您始终可以调用它们。例如:
Guid guid = new Guid();
如果你有:
public void Foo<T>() where T : new()
调用完全有效
Foo<Guid>();
关于c# - 泛型实现中的值和引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30110417/