为什么:
string s = "";
bool sCanBeNull = (s is Nullable);
s = null;
Run Code Online (Sandbox Code Playgroud)
sCanBeNull 等于假?
我正在编写代码生成器,并且需要确保传递给它的每个类型都可以为空(如果还没有).
//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;
}
Run Code Online (Sandbox Code Playgroud)
我是否需要明确检查字符串或我错过了什么?
is 告诉您某个值是特定类型还是从该特定类型派生的值.
Nullable是一个通用的struct,允许可空值的非可空值.
string 不是一个 Nullable
要判断某个类型是否具有null值,请使用以下事实:对于所有此类类型,默认值为null,而对于所有其他类型,则不是:
default(string) == null; // true
Run Code Online (Sandbox Code Playgroud)