2011-09-08 65 views

回答

4

int?Nullabe<int>简写。

Nullable<T>是一个值类型,泛型类型参数也必须是值类型。

可为空的类型可以包含一个值,或根本不包含任何值,例如,

int? i; // same as Nullable<int> i; 
Console.WriteLine("i.HasValue={0}", i.HasValue); // Writes i.HasValue=False 
i = 10; 
Console.WriteLine("i.HasValue={0}", i.HasValue); // Writes i.HasValue=True 

您可以使用?运算符(即null-coalescing operator)与Nullable类型。

int? i; // i has no value 
// Now we want to add 10 to i, and put it in a, however 
// a = i + 10 cannot work, because there is no value in i 
// so what value should be used instead? 
// We could do the following 
int a = 10; 
if(i.HasValue) 
    a += (int)i; 

// or we could use the ?? operator, 
int a = (i ?? 0) + 10; // ?? returns value of i, or 0 if I has no value 

该?? ??运算符允许我们使用可为空的类型,并在没有价值的情况下直接提供有意义的替代。