为什么接受引用类型的泛型方法不接受可空类型作为参数?
Why generic method that accept reference types doesn't accept nullable-types as arguments?
一目了然,
public static class Conversion
{
public static T Read<T>(object value) where T :class
{
if (value is DBNull) return null;
if (value is null) return null;
if (value is Enum) return (T)Enum.Parse(typeof(T), value.ToString(), true);
return (T)Convert.ChangeType(value, typeof(T));
}
}
当调用Read<T>
函数时
var myVariable = Conversion.Read<bool?>(Row[nameof(IsFetchNextRecordAfterDelete)]);
Error CS0452 The type 'bool?' must be a reference type in order to use
it as parameter 'T' in the generic type or method
'Conversion.Read(object)'
想知道为什么?布尔值?可以为空,这意味着它是一个引用类型,并且声明了泛型方法 where T : class
'bool?' 不是 引用类型。它是一个可为 null 的 value 类型。
见 Nullable value types (C# reference)
底层类型是一个结构(它是一个值类型)。
where T :class
此约束意味着您将提供的类型参数将是包括任何 class、接口、委托或数组类型的引用类型。
Type Constraints
可空类型属于值类型类别,不作为参考。
一目了然,
public static class Conversion
{
public static T Read<T>(object value) where T :class
{
if (value is DBNull) return null;
if (value is null) return null;
if (value is Enum) return (T)Enum.Parse(typeof(T), value.ToString(), true);
return (T)Convert.ChangeType(value, typeof(T));
}
}
当调用Read<T>
函数时
var myVariable = Conversion.Read<bool?>(Row[nameof(IsFetchNextRecordAfterDelete)]);
Error CS0452 The type 'bool?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Conversion.Read(object)'
想知道为什么?布尔值?可以为空,这意味着它是一个引用类型,并且声明了泛型方法 where T : class
'bool?' 不是 引用类型。它是一个可为 null 的 value 类型。 见 Nullable value types (C# reference) 底层类型是一个结构(它是一个值类型)。
where T :class
此约束意味着您将提供的类型参数将是包括任何 class、接口、委托或数组类型的引用类型。 Type Constraints
可空类型属于值类型类别,不作为参考。