Pho*_*Sho 4 c# oop interface ref
我想知道为什么这是一个编译错误,以便更好地理解C#语言.
在我的代码中,我有一个从IDisposable派生的接口(IMyInterface).我有另一种方法,它采用'ref IDisposable'类型的参数.但我不能将IMyInterface类型的成员var传递给该方法.这是我的示例代码如下:
using System;
namespace CompileErrorBaseInterface
{
public interface IMyInterface : IDisposable { }
class Program
{
private IMyInterface _myInterfaceObj;
static void Main(string[] args) { }
public void ExampleMethod()
{
MyMethodBaseInterface(ref _myInterfaceObj); //compile error
MyMethodDerivedInterface(ref _myInterfaceObj); //no compile error
}
private void MyMethodBaseInterface(ref IDisposable foo) { }
private void MyMethodDerivedInterface(ref IMyInterface foo) { }
}
}
Run Code Online (Sandbox Code Playgroud)
编译错误是:
任何人都可以解释为什么这是不允许的,或者编译器无法做到这一点?我有一个使用泛型的解决方法,所以我只想了解为什么不允许这样做.
谢谢.
请考虑以下示例:
private void MyMethod(ref IDisposable foo)
{
// This is a valid statement, since SqlConnection implements IDisposable
foo = new SqlConnection();
}
Run Code Online (Sandbox Code Playgroud)
如果您被允许传递IMyInterface给MyMethod,那么您就会遇到问题,因为您只是将类型的对象SqlConnection(未实现IMyInterface)分配给类型的变量IMyInterface.
有关更多详细信息,请查看C#guru Eric Lippert的以下博客条目: