Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在函数中初始化数组_C#_Arrays_Function - Fatal编程技术网

C# 在函数中初始化数组

C# 在函数中初始化数组,c#,arrays,function,C#,Arrays,Function,嗨,我有这样的代码 int[] n1 = new int[] {2, 4, 6, 8}; char[] n2 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' }; public static void myTest(int[] n1, char[] n2) { ......... } 我想把2个变量传递给函数 像这样 int[] n1 = new int[] {2, 4, 6, 8}; char[] n2 = { 'A', 'B',

嗨,我有这样的代码

int[] n1 = new int[] {2, 4, 6, 8};
char[] n2 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
 public static void myTest(int[] n1, char[] n2) 
 {
  .........
 }
我想把2个变量传递给函数 像这样

int[] n1 = new int[] {2, 4, 6, 8};
char[] n2 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
 public static void myTest(int[] n1, char[] n2) 
 {
  .........
 }
问题是我不能用这段代码初始化函数中的数组

 n1 = {2, 4, 6, 8};
 n2 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
 //or with this one
 n1[] = {2, 4, 6, 8};
 n2[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
我在哪里失踪了?

或者如何正确执行此操作?

您只能在创建数组时使用数组初始化语法

您可以使用新内容创建一个新的:

n1 = new[] {2, 4, 6, 8};
n2 = new[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
更新

但是,它不会更新作为参数传递给方法的变量。要做到这一点,您必须使用
ref
关键字通过ref传递它们:

public static void myTest(ref int[] n1, ref char[] n2) 
{
    n1 = new[] {2, 4, 6, 8};
    n2 = new [] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
}

此处不应使用
ref
关键字,而应使用
out
关键字。为什么会这样

使用
ref
时,需要在将值传递到方法之前初始化值-例如:

var arrayInt = new int[0];
var arrayChar = new char[0];

MyTest(ref arrayInt, ref arrayChar);
MyTest
定义为
MyTest(ref int[]n1,ref char[]n2){…}

当使用
out
关键字时,您可以将单位化值传递到方法中:

int[] arrayInt;
char[] arrayChar;

MyTest(out arrayInt, out arrayChar);
使用
MyTest
定义如下:

public static void MyTest(out int[] n1, out char[] n2) 
{
    n1 = new[] {2, 4, 6, 8};
    n2 = new[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
}

这毫无意义。您希望将已初始化的数组传递到函数中。。但是你是说你不能在函数中初始化它们?我不知道你在说什么。你试过
n1=new[]{…}?但即便如此,正如@Simon所说,这也没有多大意义。将它们作为参数传递是无用的,因为它们将在方法体中被覆盖。除非您在新初始化之前确实使用n1和n2。@SimonWhitehead抱歉,如果我的问题不清楚,我的意思是在parrent中,我只想声明数组,然后在函数中初始化它……不在父函数和函数中初始化,您需要将其作为
ref
传递。它的工作方式与charmWorks类似,但可能没有用。调用方法中的数组不会被分配到,除非您使用
ref
关键字。@Lucmorin先生是的……在我尝试我的项目后,它实际上是无用的,所以我尝试了不同的方法way@katik如果可以的话,我会邀请你认真考虑别人对你的问题提出的意见,而不是跳转似乎是正确的答案,这显然是错误的,在这种情况下。“卢克摩林嗯……同意我必须做什么?”删除此解决方案中的正确答案或。。。?