【问题标题】:Pass infinite params by reference (using keywords params and ref together)通过引用传递无限参数(同时使用关键字 params 和 ref)
【发布时间】:2016-03-03 14:38:42
【问题描述】:

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

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

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 }

【问题讨论】:

  • 不,C# 中不能有引用数组。
  • 好的...我刚刚点击了“发布您的问题”按钮...甚至没有时间刷新我的浏览器并发布了此评论。
  • 我不确定这是否重复但相似:stackoverflow.com/questions/1776020/…
  • @LucasTrzesniewski:嗯,你可以有一个引用数组。但是你不能有一个引用参数数组:)
  • 请注意,在第二个示例中,您不需要 ref 来改变单个对象,或将新对象分配给数组。仅当您想将新数组分配给tests 时才需要它。它不允许您更改test1test2test3 指向的任何一种方式的引用。也许您应该告诉我们您打算如何处理 Test 中的数组。

标签: c# object reference .net-4.0 params-keyword


【解决方案1】:

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

这样的功能应该有什么好处?很明显,您需要一种可以更改 any 对象的方法,无论它来自哪里,也无论谁在使用它。这几乎不是一个类的Single-Responsibility-principle 的休息,使其成为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

【讨论】:

  • 谢谢,这确实解释了 IEnumerable 方法,但对我使用 Test() 函数的方式没有帮助。在我的例子中(虽然很简单)并不代表函数的意图。我想让问题保持简单以获得简单的答案(我做到了,这就是为什么如果你加粗“所以简单的答案......”这一行我会接受你的答案)我不认为它像“上帝对象”虽然......我的意图是把一堆对象写入一个字节数组。就像我说的,我已经可以做到了。只是想让它更快/更简单。
猜你喜欢
  • 2017-02-11
  • 2015-03-13
  • 2011-03-25
  • 1970-01-01
  • 2014-07-23
  • 2013-12-31
  • 2013-07-18
  • 2010-12-13
相关资源
最近更新 更多