通过引用传递无限参数(一起使用关键字参数和引用)

本文关键字:引用 参数 关键字 一起 无限 | 更新日期: 2023-09-27 18:37:09

是否有可能通过引用将无限数量的参数传递给我的函数?

我知道这是无效的,但是有没有办法做到这一点?

private bool Test(ref params object[] differentStructures)
{
    //Change array here and reflect changes per ref
}
TestStructOne test1 = default(TestStructOne);
TestStructTwo test2 = default(TestStructTwo);
TestStructOne test3 = default(TestStructOne);
if (Test(test1, test2, test3)) { //happy dance }

我知道我可以执行以下操作,但我希望消除必须创建一个额外的变量来包含所有对象......

private bool Test(ref object[] differentStructures)
{
    //Change array here and reflect changes per ref
}
TestStructOne test1 = default(TestStructOne);
TestStructTwo test2 = default(TestStructTwo);
TestStructOne test3 = default(TestStructOne);
object[] tests = new object[] { test1, test2, test3 };
if (Test(ref tests)) { //simi quazi happy dance }

通过引用传递无限参数(一起使用关键字参数和引用)

所以简单的答案是否定的,你不能让一个方法返回无限数量的引用。

这样的功能应该有什么好处?显然,你想要一种方法,可以改变任何对象,无论它来自哪里,也无论谁在使用它。这几乎不是对一个阶级的单一责任原则的突破,使其成为上帝对象。

但是,您可以做的是在枚举中创建实例:

private bool Test(object[] differentStructures)
{
    differentStructures[0] = someOtherRessource;
    differentStructures[1] = anotherDifferentRessource
    differentStructures[2] = thirdDifferentRessource
}

并像这样称呼它:

var tests = new[] {
    default(TestStructOne),
    default(TestStructTwo),
    default(TestStructOne)
}
Test(tests);

这将导致以下内容:

tests[0] = someOtherRessource;
tests[1] = anotherDifferentRessource
tests[2] = thirdDifferentRessource