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
orSystem.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/