接口顺序的重要性

  • 本文关键字:重要性 顺序 接口 c#
  • 更新时间 :
  • 英文 :


我有一个不明白的编译问题。我将生成代码以使其更易于遵循,我希望我不会失去意义。 错误是:

MyInterface1 does not contain definition for 'MyClass1'

这是正确的,因为MyClass1MyInterface2.如果我像这样切换接口的顺序:

public partial class MyPresenter : ParentPresenter<MyInterface2>, ParentPresenter<MyInterface1>

然后编译。这是怎么回事?

第一个文件:

namespace MyNameSpace
{
    public partial class MyPresenter :  ParentPresenter<MyInterface1>, ParentPresenter<MyInterface2>
    {
        public MyClass1 MyClass1 { get; set; }
        public void MyMethod() {
            View.MyClass1 = this.MyClass1; // compile error on View.MyClass1
      }
    }
}

第二个文件:

namespace MyNameSpace
{
    public interface MyInterface1
    {
        System.Collections.IList MyList1 { set; }
    }
    public interface MyInterface2
    {
        MyClass1 MyClass1 { set; }
        System.Collections.IList MyList2 { set; }
    }
}

文件3:

public abstract class ParentPresenter<TView> : System.IDisposable
{
    private TView _view;
    private Microsoft.Practices.CompositeUI.WorkItem _workItem;
    public TView View
    {
        get { return this._view; }
        set
        {
            this._view = value;
            this.OnViewSet();
        }
    }
}

编辑:将二传手添加到MyClass1

编辑后问题很明显。

您正在执行:

public partial class MyPresenter :  ParentPresenter<MyInterface1>

因此,这意味着您的类继承自:

public abstract class ParentPresenter<TView> : System.IDisposable

TViewMyInterface1的地方.

因此,您的View属性现在是类型 MyInterface1 ,它没有MyClass1的定义,因此您尝试访问的编译器错误View.MyClass1

这:

public partial class MyPresenter :  
           ParentPresenter<MyInterface1>, 
           ParentPresenter<MyInterface2>

C# 不支持,这是多重继承。它只允许用于接口,但不允许用于类(在原始问题中,您实现了两个接口,这是受支持的:在编辑之后,您尝试从两个类继承,但不是)。

但是,您可以执行以下操作:

public interface MyInterface3 : MyInterface1, MyInterface2
{
}

然后你可以做:

public partial class MyPresenter : ParentPresenter<MyInterface3>

这意味着您的View必须实现两个接口(MyInterface1MyInterface2),并声明为实现MyInterface3(C#也不支持鸭子类型),但从外观上看,它已经实现了所有必要的东西。

最新更新