C#为什么我不能通过ref传递"base"接口?

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)

编译错误是:

  • 参数1:无法从'ref CompileErrorBaseInterface.IMyInterface'转换为'ref System.IDisposable'最佳重载方法匹配
  • 'CompileErrorBaseInterface.Program.MyMethodBaseInterface(ref System.IDisposable)'有一些无效的参数

任何人都可以解释为什么这是不允许的,或者编译器无法做到这一点?我有一个使用泛型的解决方法,所以我只想了解为什么不允许这样做.

谢谢.

Hei*_*nzi 7

请考虑以下示例:

private void MyMethod(ref IDisposable foo)
{
    // This is a valid statement, since SqlConnection implements IDisposable
    foo = new SqlConnection();
}
Run Code Online (Sandbox Code Playgroud)

如果您被允许传递IMyInterfaceMyMethod,那么您就会遇到问题,因为您只是将类型的对象SqlConnection(未实现IMyInterface)分配给类型的变量IMyInterface.

有关更多详细信息,请查看C#guru Eric Lippert的以下博客条目: