gpt4 book ai didi

c# - 声明一个变量(作为新变量)然后初始化它和直接初始化它有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 20:45:34 26 4
gpt4 key购买 nike

我见过人们使用几种不同的方式来初始化数组:

string[] Meal = new string[]{"Roast beef", "Salami", "Turkey", "Ham", "Pastrami"};

或者另一种方式,也称为初始化是:

string[] Meats = {"Roast beef", "Salami", "Turkey", "Ham", "Pastrami" };

什么是最好的方式,两种方式(包括内存分配)的主要区别是什么?

最佳答案

这两种情况没有区别。编译器生成相同的字节码(newarr OpCode):

public static void Main()
{
string[] Meal = new string[] { "Roast beef", "Salami", "Turkey", "Ham", "Pastrami"};
string[] Meats = { "Roast beef", "Salami", "Turkey", "Ham", "Pastrami" };
}

MSIL:

.entrypoint
// Code size 100 (0x64)
.maxstack 3
.locals init ([0] string[] Meal,
[1] string[] Meats,
[2] string[] CS$0$0000)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: newarr [mscorlib]System.String
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.0
IL_000a: ldstr "Roast beef"
IL_000f: stelem.ref
IL_0010: ldloc.2
IL_0011: ldc.i4.1
IL_0012: ldstr "Salami"
IL_0017: stelem.ref
IL_0018: ldloc.2
IL_0019: ldc.i4.2
IL_001a: ldstr "Turkey"
IL_001f: stelem.ref
IL_0020: ldloc.2
IL_0021: ldc.i4.3
IL_0022: ldstr "Ham"
IL_0027: stelem.ref
IL_0028: ldloc.2
IL_0029: ldc.i4.4
IL_002a: ldstr "Pastrami"
IL_002f: stelem.ref
IL_0030: ldloc.2
IL_0031: stloc.0
IL_0032: ldc.i4.5
IL_0033: newarr [mscorlib]System.String
IL_0038: stloc.2
IL_0039: ldloc.2
IL_003a: ldc.i4.0
IL_003b: ldstr "Roast beef"
IL_0040: stelem.ref
IL_0041: ldloc.2
IL_0042: ldc.i4.1
IL_0043: ldstr "Salami"
IL_0048: stelem.ref
IL_0049: ldloc.2
IL_004a: ldc.i4.2
IL_004b: ldstr "Turkey"
IL_0050: stelem.ref
IL_0051: ldloc.2
IL_0052: ldc.i4.3
IL_0053: ldstr "Ham"
IL_0058: stelem.ref
IL_0059: ldloc.2
IL_005a: ldc.i4.4
IL_005b: ldstr "Pastrami"
IL_0060: stelem.ref
IL_0061: ldloc.2
IL_0062: stloc.1
IL_0063: ret

关于c# - 声明一个变量(作为新变量)然后初始化它和直接初始化它有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16106757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com