我在C#中读到了大约notnull
个约束,上面写道"这允许值类型或不可为空的引用类型,但不允许为空的引用类型."
(引用自Ian Griffiths的《Programming C#-10.0》)
我try 在以下代码中判断此约束:
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}");
}
}
正如你所看到的,我用可空类型int?
(可空值类型)和string?
(可空引用类型)实例化了我的泛型类,它仍然对我有效.
它还为我打印如下输出:
Type of T is System.Nullable`1[System.Int32] and its default value is 'Null'
Type of T is System.String and its default value is 'Null'
Type of T is System.Int32 and its default value is 0
Type of T is System.String and its default value is 'Null'"
它的行为是"字符串?"作为‘字符串’,并将两者检测为不可为空. 发生这种情况的原因可能是什么?