c# - 泛型实现中的值和引用类型

标签 c# .net oop generics types

我搜索了C# 中的泛型类型,我得出了这个结论:

  1. 所有引用类型都基于Class
  2. 所有值类型都基于struct
  3. 结构和类之间的主要区别,除了值和引用类型之间的全局区别外,还有:

    • struct中没有继承

    • 结构不能包含空构造函数(不带参数)

  4. 通用类型有六个基本实现:
  • 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

所以我需要知道:

  1. 我的结论是否正确?
  2. 我不明白 :
  3. 之间的区别
  • 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/

相关文章:

java - 从数组中删除对象并将其替换为另一个数组中的对象

java - 如何通过子类访问父类变量

c# - EPPlus - 如何使用模板

c# - 将列表中的值与另一个列表中的特定总和进行比较的最快方法是什么?

c# - 第二次调用 DirectX 中的 Device.Reset 会抛出 InvalidCallException

c# - 通过 Bot Framework 发送的英雄卡中的图像未从源更新

java - OOP 如何判断从实现的接口(interface)调用了哪个类方法

c# - 将导航 url 设置为动态超链接

c# - JsonResult 返回空 Json

c# - 如何将多个对象序列化为现有的 XmlDocument,而无需在每个组件上设置 namespace ?