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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下