c# - C# 中的所有引用类型都是类类型吗?

标签 c# class types reference

C#中是否存在不是类的引用类型?以下泛型中的约束是否包括所有引用类型?

static void f<T>() where T : class
{
    T t = default;
    Console.WriteLine(t);
}

最佳答案

您问了两个不同的问题:

Are all reference types class types in C#?

没有。

does the constraint in following generic [where T : class], includes all reference types?

是的,它将限制所有引用类型

<小时/>

首先,让我们确定引用类型实际上是什么。

Reference types (C# Reference)

There are two kinds of types in C#: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data.

The following keywords are used to declare reference types:

  • class

  • interface

  • delegate

C# also provides the following built-in reference types:

  • dynamic

  • object

  • string

注意:上面没有提到,Array类型也是从 abstract 派生的引用类型基本类型Array

其次,让我们弄清楚类约束约束什么

Constraints on type parameters (C# Programming Guide)

where T : class

The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type.

注意:上面没有提到,class约束还包括dynamic

<小时/>

作为一个额外的事实,从C# 7.3开始,您还可以通过委托(delegate)显式约束

委托(delegate)约束

Also beginning with C# 7.3, you can use System.Delegate or System.MulticastDelegate as a base class constraint. The CLR always allowed this constraint, but the C# language disallowed it

关于c# - C# 中的所有引用类型都是类类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60123012/

相关文章:

c# - 使用锁的正确位置在哪里

c# - 检查mysql数据库中是否存在

c# - 如何声明一个类型正在实现 ProtoBuf 中的接口(interface)和基类?

c# - 如何以编程方式确定是否需要 TFS WorkItem 字段?

Java:当它具有 protected 构造函数时,如何从 java.io 为 Reader 类创建新的类对象

python - 继承 namedtuple 还是实现 __slots__?

c# - 你什么时候想在 C# 中嵌套类?

vector - 我应该如何存储要从中删除但从不添加的项目列表?

c - 如何删除 char 数组转换为无符号 char 数组的警告

java - 使用哪一个,int 或 Integer