c# - 我可以有一个接口(interface)参数,通过引用传递吗?

标签 c# interface pass-by-reference

我有一个带有这个签名的方法:

protected bool MyMethod (ref IMyInterface model) {
    // stuff and things
}

我有一个从这个类传入的模型:

public class MyClass: IMyInterface {
    // class stuff and things
}

我正在尝试将我的模型传递给这样的方法:

var model = new MyClass():

MyMethod(ref model);

但是,我收到有关类型与参数类型不匹配的错误。如果我不通过引用,它工作正常。或者,如果我像这样转换并传递它,它就可以正常工作。

var tempModel = (IMyInterface)model;

MyMethod(ref tempModel);

如果没有必要,我宁愿避免强制转换,但没有它我无法通过。我想如果类实现了接口(interface),我就可以传递模型。这不是我可以通过引用做的事情,还是我遗漏了什么?

最佳答案

如果您不使用隐式类型,而只是将您的变量定义为接口(interface),它将起作用:

IMyInterface model = new MyClass():

MyMethod(ref model);

ref 传递的参数必须与类型完全匹配,因为它们可以在方法内重新分配给与该协定匹配的另一种类型。在你的情况下,这是行不通的。想象一下:

protected bool MyMethod (ref IMyInterface model) 
{
    // This has to be allowed
    model = new SomeOtherMyInterface();
}

// Now, in your usage:
var model = new MyClass(); // Exactly the same as MyClass model = new MyClass();

MyMethod(ref model); // Won't compile...

// Here, model would be defined as `MyClass` but have been assigned to a `SomeOtherMyInterface`, hence it's invalid...

关于c# - 我可以有一个接口(interface)参数,通过引用传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29268908/

相关文章:

c# - 一项服务,两种行为配置

c# - Visual Studio 项目文件指定多次导入

c# - 使用 Roslyn 确定类是否为记录

java - 从具有相同方法签名的多个接口(interface)继承的类

javascript - 函数参数变成对象的名称而不是其引用

c# - 无法将类型为 'System.Byte[]' 的对象转换为类型 'System.IConvertible'

c# - 如何在运行时确定接口(interface)成员是否已实现?

function - 添加到 []interface{} 的对象。现在需要获取对象并调用对象各自的 Display() fn

传递给构造函数的临时对象的 C++ 生命周期

javascript - 当我明确表示我不希望它通过引用传递数组时