【问题标题】:Difference between using new in arrays in C# [duplicate]在 C# 中在数组中使用 new 之间的区别 [重复]
【发布时间】:2021-07-05 23:03:25
【问题描述】:

在声明一个新数组时使用关键字new与不使用它有什么区别?我在互联网上看到了类似的东西,但没有完全理解其中的区别: 使用此语法的赋值右侧的 new 关键字。这仅在数组声明期间才有可能。

例如:

string[] names = {"Joe", "Sally", "Thomas"};

string[] names = new string[] {"Joe", "Sally", "Thomas"};

【问题讨论】:

  • 这能回答你的问题吗? All possible array initialization syntaxes
  • 没有区别; C# 语言语法——随着更高版本越来越多——只允许您使用更紧凑/简洁的版本,而更详细的版本中的额外位几乎没有增加价值。

标签: c# arrays .net


【解决方案1】:

区别在于“新字符串[]”。

我的意思是,它们的作用完全相同:

string[] names = new string[3] {"Joe", "Sally", "Thomas"};
string[] names = new string[] {"Joe", "Sally", "Thomas"};
string[] names = new [] {"Joe", "Sally", "Thomas"};
string[] names = {"Joe", "Sally", "Thomas"};

现在,考虑使用var。这有效:

var names = new string[3] {"Joe", "Sally", "Thomas"};
var names = new string[] {"Joe", "Sally", "Thomas"};
var names = new [] {"Joe", "Sally", "Thomas"};

但这不是:

var names = {"Joe", "Sally", "Thomas"};

Why can't I use the array initializer with an implicitly typed variable?

【讨论】:

    【解决方案2】:

    代码编译后实际上没有区别。您应该使用哪一个取决于偏好。

    我经常使用https://sharplab.io 来比较代码的原始版本和编译版本,如下所示。

    在这种情况下,编译器能够根据变量声明string[] names1 来判断新数组应该是什么类型。

    您的原始代码:

    string[] names1 = {"Joe", "Sally", "Thomas"};
    
    string[] names2 = new string[] {"Joe", "Sally", "Thomas"};
    

    编译后:

    string[] array = new string[3];
    array[0] = "Joe";
    array[1] = "Sally";
    array[2] = "Thomas";
    string[] array2 = new string[3];
    array2[0] = "Joe";
    array2[1] = "Sally";
    array2[2] = "Thomas";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2017-09-02
      • 2016-10-04
      • 2015-07-01
      • 2012-12-12
      • 2013-12-20
      • 1970-01-01
      相关资源
      最近更新 更多