通过引用传递无限参数(同时使用关键字 params 和 ref)

Pass infinite params by reference (using keywords params and ref together)

是否可以通过引用将无限数量的参数传递到我的函数中?

我知道这是无效的,但是有办法吗?

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 }

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

这样的功能应该有什么好处?显然,您需要一种可以更改 any 对象的方法,无论它来自何处,也无论是谁在使用它。这几乎算不上 Single-Responsibility-principle of a class, making it a God-object 的突破。

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

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