【发布时间】: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时才需要它。它不允许您更改test1、test2和test3指向的任何一种方式的引用。也许您应该告诉我们您打算如何处理Test中的数组。
标签: c# object reference .net-4.0 params-keyword