我读过有关notnullC# 中的约束的内容,其中写道“这允许值类型或不可为空的引用类型,但不允许可为空的引用类型。” (引用自《Programming C# - 10.0 By Ian Griffiths》)
我尝试在下面的代码中检查这个约束:
MyTestClass<int?> instance1 = new MyTestClass<int?>();
MyTestClass<string?> instance2 = new MyTestClass<string?>();
public class MyTestClass<T> where T : notnull
{
T Value { get; set; }
public MyTestClass()
{
Value = default(T);
if (Value == null)
Console.WriteLine($"Type of T is {typeof(T)} and its default value is 'Null'");
else
Console.WriteLine($"Type of T is {typeof(T)} and its default value is {Value}");
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我使用可为空类型int?(可为空值类型)和string?(可为空引用类型)实例化了我的泛型类,它仍然适用于我。
它还为我打印这样的输出:
Type of T …Run Code Online (Sandbox Code Playgroud)