C# 使用参考值作为参数,带或不带;参考号;?

C# 使用参考值作为参数,带或不带;参考号;?,c#,interface,pass-by-reference,C#,Interface,Pass By Reference,我遇到了两种解决方案(都有效): 公共列表foo1(参考接口[]全部) 或 公共列表foo2(接口[]全部) 有什么不同吗,我选哪一个重要吗?接口是一个参考值,无论如何都会将参数作为参考,并且“ref”也会得到参考…我想我可以忽略“ref”。。。我想知道为什么编译器没有给我一个错误…在第一种情况下,您将替换“全局”(方法外)参数all。在第二种情况下,您将替换all参数的本地副本 public List<Label> foo1(ref ISomeInterface[] all)

我遇到了两种解决方案(都有效):

公共列表foo1(参考接口[]全部)

公共列表foo2(接口[]全部)
有什么不同吗,我选哪一个重要吗?接口是一个参考值,无论如何都会将参数作为参考,并且“ref”也会得到参考…我想我可以忽略“ref”。。。我想知道为什么编译器没有给我一个错误…

在第一种情况下,您将替换“全局”(方法外)参数
all
。在第二种情况下,您将替换
all
参数的本地副本

public List<Label> foo1(ref ISomeInterface[] all)
{
    all = new ISomeInterface[0]; //you will get empty array outside method
}

public List<Label> foo1(ISomeInterface[] all)
{
    all = new ISomeInterface[0]; //you will get empty array only inside method
}
公共列表foo1(参考接口[]全部)
{
all=新接口[0];//将在方法外部获得空数组
}
公共列表foo1(接口[]全部)
{
all=新接口[0];//仅在方法内部获得空数组
}
有区别吗

是的,有。C#中的所有内容都通过值传递。通过
ref
传递引用类型时,传递的是实际引用指针,而不是副本。这样,如果您通过
ref
传递引用类型,并通过
new
关键字将其设置为新引用,您将更改引用

例如:

public static void Main(string[] args)
{
    ISomeInterface[] somes = new[] { new SomeConcreteType() }
    Foo(somes);
    Console.WriteLine(somes.Length) // Will print 1
    Foo(ref somes);
    Console.WriteLine(somes.Length) // Will print 0
}

public List<Label> Foo(ref ISomeInterface[] all)
{
    all = new ISomeInterface[0];
}
public List<Label> Foo(ISomeInterface[] all)
{
    all = new ISomeInterface[0];
}
publicstaticvoidmain(字符串[]args)
{
ISomeInterface[]somes=new[]{new SomeConcreteType()}
Foo(somes);
Console.WriteLine(somes.Length)//将打印1
Foo(参考somes);
Console.WriteLine(somes.Length)//将打印0
}
公共列表Foo(参考接口[]全部)
{
all=新接口[0];
}
公共列表Foo(接口[]全部)
{
all=新接口[0];
}

这取决于您希望对阵列执行的操作。 如果要修改foo1方法中的值并在foo1方法之外使用这些修改,则可能需要使用
ref
类型版本


如果您只想使用返回的
列表
您应该使用不带ref的选项。

只是我这边的一个小问题:在C#中是否总是“按值调用”,即使对于数组也是如此?我的意思是这听起来很不寻常,但有可能。这意味着它需要在函数调用时将整个数组复制到堆栈中,而不使用ref.@Matthias id始终按值调用。但它不会复制数组,它只会将引用(指针)复制到数组。这里,value只是一个小pointerOK。所以这只是指针而不是有效载荷。我认为如果它不复制数组,它应该被称为“引用调用”?@Matthias似乎没有,但没有。这是一个指针。他的值是数组的地址。当您在不使用
ref
的情况下调用时,您传递值并将其复制到具有相同值(相同数组的地址)的本地指针。您可以修改此本地指针(使用
new
),它不会影响具有相同值(数组地址)的另一个变量。当您传递ny
ref
时,您没有额外的局部变量。这是“参考电话”
public List<Label> foo1(ref ISomeInterface[] all)
{
    all = new ISomeInterface[0]; //you will get empty array outside method
}

public List<Label> foo1(ISomeInterface[] all)
{
    all = new ISomeInterface[0]; //you will get empty array only inside method
}
public static void Main(string[] args)
{
    ISomeInterface[] somes = new[] { new SomeConcreteType() }
    Foo(somes);
    Console.WriteLine(somes.Length) // Will print 1
    Foo(ref somes);
    Console.WriteLine(somes.Length) // Will print 0
}

public List<Label> Foo(ref ISomeInterface[] all)
{
    all = new ISomeInterface[0];
}
public List<Label> Foo(ISomeInterface[] all)
{
    all = new ISomeInterface[0];
}