C#基础语法:可空类型详解
以下是System.Nullable<T>在FCL中的定义。
[Serializable,StructLayout(LayoutKind.Sequential)]
publicstructNullable<T>whereT:struct
{
privateBooleanhasValue=false;
internalTvalue=default(T);
publicNullable(Tvalue)
{
this.value=value;
this.hasValue=true;
}
publicBooleanHasValue{get{returnhasValue;}}
publicTValue
{
get
{
if(!hasValue)
{
thrownewInvalidOperationException("Nullableobjectmusthaveavalue.");
}
returnvalue;
}
}
publicTGetValueOrDefault(){returnvalue;}
publicTGetValueOrDefault(TdefaultValue)
{
if(!HasValue)returndefaultValue;
returnvalue;
}
publicoverrideBooleanEquals(objectother)
{
if(!HasValue)return(other==null);
if(other==null)returnfalse;
returnvalue.Equals(other);
}
publicoverrideintGetHashCode()
{
if(!HasValue)return0;
returnvalue.GetHashCode();
}
publicoverridestringToString()
{
if(!HasValue)return"";
returnvalue.ToString();
}
publicstaticimplicitoperatorNullable<T>(Tvalue)
{
returnnewNullable<T>(value);
}
}
可以看出null的类型的每个实例都具有两个公共的只读属性:
1.HasValue
HasValue属于bool类型。当变量包含非null值时,它被设置为true。
2.Value
Value的类型与基础类型相同。如果HasValue为true,则说明Value包含有意义的值。如果HasValue为false,则访问Value将引发InvalidOperationException。
那么我们怎么定义可空类型?
null的类型可通过下面两种方式中的一种声明:
System.Nullable<T>variable
-或-
T?variable