为什么:
string s = "";
bool sCanBeNull = (s is Nullable);
s = null;
sCanBeNull
等于 false?
我正在编写一个代码生成器,需要确保传递给它的每个类型都可以为 null,如果不是的话。
//Get the underlying type:
var type = field.FieldValueType;
//Now make sure type is nullable:
if (type.IsValueType)
{
var nullableType = typeof (Nullable<>).MakeGenericType(type);
return nullableType.FullName;
}
else
{
return type.FullName;
}
我是否需要显式检查字符串,或者我是否遗漏了什么?
最佳答案
is
告诉您一个值是属于特定类型还是派生自该特定类型。
Nullable
是一个通用的 struct
,它允许非可空值的可空版本。
string
不是 Nullable
要判断一个类型是否可以具有 null
值,请使用以下事实:对于所有此类类型,默认值为 null
,而对于所有其他类型,则不是:
default(string) == null; // true
关于c# - 字符串为 Nullable 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32498732/