【发布时间】:2013-02-08 02:13:35
【问题描述】:
有人可以向我解释为什么这在 C# 中不正确:
namespace NamespaceA
{
public class ClassA
{
public interface IInterfaceA
{
String Property
{
set;
}
}
}
}
namespace NamespaceB
{
public class ClassB
{
public class ImpA: NamespaceA.ClassA.IInterfaceA
{
private String mProperty;
public String Property{ set{ mProperty = value; } }
}
public ClassB()
{
ImpA aImpA = new ImpA();
foo(ref aImpA);
}
private void foo(ref NamespaceA.ClassA.IInterfaceA aIInterfaceA)
{
aIInterfaceA.Property = "SomeValue";
}
}
}
这将产生以下编译错误:
错误参数 1:无法从 'NamespaceB.ClassB.ImpA' 转换为 'ref NamespaceA.ClassA.IInterfaceA'
想要修改接口属性并从foo() 调用接口函数似乎是完全合理的。如果您删除 ref 关键字,它会编译,但您在 foo() 中所做的更改会丢失...
【问题讨论】:
-
什么?你不需要 ref 来操作对象的属性。
-
必须同意@HighCore - 这里完全不需要 ref。
-
我将标题从 reference 编辑为
ref。 C# 与 Java 和 Python 一样,使用 Call By Object Sharing 语义传递对象。这与 Call by Reference 无关(这是ref所做的)。请参阅以前的 cmets。
标签: c# interface reference argument-passing