2010-08-07 38 views

回答

24

这被称为空合并运算符和它充当以下,假定a是一个可为空int和b是一个正常的INT

b = a ?? 1; 

等于

b = (a != null ? (int)a : 1); 

等于

if(a != null) 
    b = (int)a; 
else 
    b = 1; 

因此

public NameValueCollection Metadata 
{ 
    get { return metadata ?? (metadata = new NameValueCollection()); } 
} 

扩大看起来应该像这样

public NameValueCollection Metadata 
{ 
    get 
    { 
     if(metadata == null) 
      return (metadata = new NameValueCollection()); 
     else 
      return metadata; 
    } 
} 

这是某种一个衬垫Singleton模式,因为吸气回报元数据(一个初始化的NameValueCollection对象)每次请求时,期望第一次它在那个时候是空的,所以它初始化它并且然后返回它。这是主题,但请注意,这种单身模式的方法不是线程安全的。

0

这是coalesce操作符,它检查null。

statement ?? fallback如果语句评估为null,则使用fallback。请参阅msdn

-1

??是空合并运算符

读到它在这里: link text

+0

Downvote因为没有解释

X = (if Y is not null return Y) ?? (else return DEFAULT) 

读取详细的讨论。 – problemofficer 2016-05-19 23:00:00

4

?? Operator (C# Reference)

的?运算符称为 空合并运算符,并且使用 来定义空值类型以及 引用类型的默认值。如果它不为空,则返回 左侧的操作数; 否则返回正确的 操作数。

你的实例可以被重新写为:

public NameValueCollection Metadata 
    { 
    get { 
      if (metadata == null) 
       metadata = new NameValueCollection(); 

      return metadata; 
     } 
    } 
2

从MSDN:http://msdn.microsoft.com/en-us/library/ms173224.aspx

甲空类型可以包含值,或者它可以是不明确的。 ?? ??运算符定义将可空类型分配给非空类型时要返回的默认值。如果您尝试将空值类型分配给非空值类型而不使用?运算符,则会生成编译时错误。如果您使用强制转换,并且可以为空的值类型当前未定义,则将引发InvalidOperationException异常。

class NullCoalesce 
{ 
static int? GetNullableInt() 
{ 
    return null; 
} 

static string GetStringValue() 
{ 
    return null; 
} 

static void Main() 
{ 
    // ?? operator example. 
    int? x = null; 

    // y = x, unless x is null, in which case y = -1. 
    int y = x ?? -1; 

    // Assign i to return value of method, unless 
    // return value is null, in which case assign 
    // default value of int to i. 
    int i = GetNullableInt() ?? default(int); 

    string s = GetStringValue(); 
    // ?? also works with reference types. 
    // Display contents of s, unless s is null, 
    // in which case display "Unspecified". 
    Console.WriteLine(s ?? "Unspecified"); 
} 

}

+0

如果您要引用MSDN,请提供链接。 – strager 2010-08-07 16:06:56