C#传递可变数量的引用参数

jef*_*eff 7 c# parameters

在C#.NET中,有没有办法将可变数量的对象作为引用对象传递?例如:

MyMethod (ref param1, ref param2, ref param3)
Run Code Online (Sandbox Code Playgroud)

......具有各种类型的任意数量的参数.

Mic*_*Liu 6

如果您愿意在C#中使用未记录的关键字__arglist__refvalue关键字,则可以.

警告:未记录的功能在将来的C#版本中可能会发生变化.只有在必要时才使用这些关键字,了解如果Microsoft在下一版本中更改其行为,您的代码可能会停止工作.

例如,以下程序通过int引用该GetRandomValues方法传递三个变量.它输出2,1和4,表明变量已成功修改.

static void Main()
{
    int x = 0, y = 0, z = 0;
    GetRandomValues(__arglist(ref x, ref y, ref z));
    Console.WriteLine(x);
    Console.WriteLine(y);
    Console.WriteLine(z);
}

static void GetRandomValues(__arglist)
{
    Random random = new Random(1);
    ArgIterator iterator = new ArgIterator(__arglist);
    while (iterator.GetRemainingCount() > 0)
    {
        TypedReference r = iterator.GetNextArg();
        __refvalue(r, int) = random.Next(0, 10);
    }
}
Run Code Online (Sandbox Code Playgroud)


das*_*ght 5

不,这是不可能的:可变数量的参数在传递数组之上被实现为"语法糖"; 不可能创建一个pass-by-reference参数数组,因为"by reference by reference"不是一个类型的属性.