为什么不能将通用类型转换为null? [英] Why can't I cast generic-type with null?
问题描述
一个类似问题,但是而不使用T参数.
A similar question, but without casting the T parameter.
这不起作用
public T GetValueG<T>(string Query)
{
object value = DBNull.Value; // Read from Database which can return DBNull
if (value is DBNull)
return (T)null;
else
return (T)value;
}
错误CS0037无法将null转换为'T',因为它是不可为空的值类型
Error CS0037 Cannot convert null to 'T' because it is a non-nullable value type
但这可行
public T GetValueG<T>(string Query)
{
object value = DBNull.Value; // Read from Database which can return DBNull
if (value is DBNull)
value = null;
return (T)value;
}
我知道使用约束类型where T: struct
将使T能够直接使用null进行强制转换.
I know that using constraint type where T: struct
will make T to be able to be cast with null directly.
但是在第二种方法中,为什么它接受100%可以为null的对象?为什么我不能在没有对象或任何东西的情况下直接返回null?
But in the second approach, why does it accept an object which is 100% can be null? Why can't I return null directly without an object or something either?
推荐答案
您尝试执行的操作是错误的.整数是不可为null的类型,这意味着您不能将null作为int的值或任何其他不可为null的类型返回(如名称所示).
What you're trying to do is wrong. Integers are non-nullable types, meaning you can't return null as a value of int or any other not nullable type (as the name suggests...)
例如:
int myInt = null;
-您的IDE会立即将其标志为integer(非空类型).
int myInt = null;
- your IDE will right away flag it up with integer being a non-nullable type.
您想要做的是使用您要使用的实际类型的可空类型,例如int?
或bool?
.
What you want to do is use a nullable type of the actual type you're trying to use e.g. int?
or bool?
.
您应该返回null
或default(T)
而不是没有意义的(T)null
,因为您不能将null转换为例如一个类类型,它将抛出Object Reference Not Set To An Instance...
.
You should be returning null
or default(T)
rather than (T)null
that doesn't make sense, as you can't cast null to e.g. a class type, it'll throw Object Reference Not Set To An Instance...
.
我会将您的功能更改为以下内容:
I would change your function to the following:
public T GetValueG<T>(string Query)
{
object value = DBNull.Value; // Read from Database which can return DBNull
if (value is DBNull)
return default(T); // `return default;` also valid since C# 7.1
return (T)value;
}
如果数据库中的值可以为null,则您的模型应该实现该类型的nullable,以避免以后产生异常.
If a value can be null in your database, then your model should be implementing a nullable of that type to avoid casting exceptions later down the line.
您的函数应这样调用GetValueG<int?>("<query>");
.
Default values for non-nullables can be found here.
在代码中,您将执行myNullableInt.HasValue
,而不是使用myInt == null
检查空值.
In your code, rather than checking for null values using myInt == null
you'd do myNullableInt.HasValue
.
摘要
默认关键字.默认情况下将为可为null的类型返回null. 以及其他非空类型的默认值.根据OP的需要.
The default keyword. will return null for nullable types by default. and default values for other non-nullable types. as OP needs.
default(bool?)
->空
default(bool)
->假
这篇关于为什么不能将通用类型转换为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!