【问题标题】:C# why can't I pass "base" interface by ref?C# 为什么我不能通过 ref 传递“base”接口?
【发布时间】:2016-07-19 17:28:15
【问题描述】:

我想知道为什么这是一个编译错误,以便更好地理解 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) { }
    }
}

编译错误是:

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

谁能解释为什么不允许这样做,或者编译器不可能这样做?我有一个使用泛型的解决方法,所以我只想了解为什么不允许这样做。

谢谢。

【问题讨论】:

    标签: c# oop interface ref


    【解决方案1】:

    考虑以下示例:

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

    如果允许您将IMyInterface 传递给MyMethod,您就会遇到问题,因为您只是将SqlConnection 类型的对象(它不实现IMyInterface)分配给了一个类型为变量的变量IMyInterface.

    有关更多详细信息,请查看以下 C# 大师 Eric Lippert 的博客文章:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多