我有一个带有这个签名的方法:
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/