C#:在方法调用中直接创建并传递变量

Bor*_*mix -1 c# syntax

我想知道如何在参数括号中直接声明新变量并将其传递给它:

MethodA(new int[]) //but how to fill the array if declared here? E.g. how to declare and set string?


MethodA(int[] Array)
...
Run Code Online (Sandbox Code Playgroud)

如果需要声明一个对象(带有构造函数参数的类)怎么办?参数列表中仍有可能吗?

djd*_*d87 7

MethodA(new int[] { 1, 2, 3 }); // Gives an int array pre-populated with 1,2,3
Run Code Online (Sandbox Code Playgroud)

要么

MethodA(new int[3]); // Gives an int array with 3 positions
Run Code Online (Sandbox Code Playgroud)

要么

MethodA(new int[] {}); // Gives an empty int array
Run Code Online (Sandbox Code Playgroud)

您可以对字符串,对象等执行相同的操作:

MethodB(new string[] { "Do", "Ray", "Me" });

MethodC(new object[] { object1, object2, object3 });
Run Code Online (Sandbox Code Playgroud)

如果要将字符串传递给方法,请执行以下操作:

MethodD("Some string");
Run Code Online (Sandbox Code Playgroud)

要么

string myString = "My string";
MethodD(myString);
Run Code Online (Sandbox Code Playgroud)

更新: 如果要将类传递给方法,可以执行以下操作之一:

MethodE(new MyClass("Constructor Parameter"));
Run Code Online (Sandbox Code Playgroud)

要么

MyClass myClass = new MyClass("Constructor Parameter");
MethodE(myClass );
Run Code Online (Sandbox Code Playgroud)