【问题标题】:Please decipher this C# expression for me请为我破译这个 C# 表达式
【发布时间】:2012-05-20 11:50:19
【问题描述】:

这是什么意思??

var cdParams = (includeUniversals) 
? new[] {pageDictionary[pageName], pageDictionary[CNNService.UniversalPage.Name]}
: new[] {pageDictionary[pageName]};

基本上归结为什么?是什么意思,new[] 是什么意思?

【问题讨论】:

  • 表达式的哪一部分有问题? ? 运算符? new[] 运算符?
  • 取决于 includeUniversals,你的 cdParam 要么是两个值的数组,要么是只有一个值的数组,你在 pageDictionary 中的值是任何类型的值

标签: c#


【解决方案1】:

大致相当于这样:

Foo[] cdParams;  // Use the correct type instead of Foo. NB: var won't work here.
if (includeUniversals) { 
    dParams = new Foo[2];
    dParams[0] = pageDictionary[pageName];
    dParams[1] = pageDictionary[CNNService.UniversalPage.Name];
} else {
    dParams = new Foo[1];
    dParams[0] = pageDictionary[pageName];
}

【讨论】:

  • @PeterLaCombJr.: new[] 表示它推断类型。它可能不是object,而是其他类型。我更新了代码以使其更加明确。
  • 猜猜我从来没有注意到这一点,而且我的使用总是导致对象[]。谢谢。
  • 再看问题,Foo大概就是Page。不管那是什么。
【解决方案2】:

这是一个ternary expression。如果条件为真,则执行第一种情况。如果为假,则执行第二种情况。

【讨论】:

    【解决方案3】:

    如果布尔值includeUniversals 的计算结果为真,则返回一个包含pageDictionary[pageName]pageDictionary[CNNService.UniversalPage.Name] 的新匿名对象数组,否则返回一个包含pageDictionary[pageName] 的新匿名对象数组

    你在找什么?

    【讨论】:

      【解决方案4】:
      var cdParams // type inferred by the compiler
       = (includeUniversals) ? // if includeUniversals is true
      
      // then cdParams = new a new array with 2 values coming from a dictionary
       new[] { pageDictionary[pageName], pageDictionary[CNNService.UniversalPage.Name] }
      
      // otherwise, cdParams = a new array with one value
      : new[] { pageDictionary[pageName] };
      

      请参阅 ternary operatorimplicit array typing

      【讨论】:

        【解决方案5】:

        取决于includeUniversalscdParams 将是一个包含两个值的数组,即pageDictionary[pageName]pageDictionary[CNNService.UniversalPage.Name] - 或者,它将是一个包含一个值的数组,即pageDictionary[pageName]

        【讨论】:

          猜你喜欢
          • 2015-11-12
          • 1970-01-01
          • 2012-01-13
          • 1970-01-01
          • 2017-01-23
          • 2017-12-29
          • 2010-10-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多