c# - 接口(interface)顺序的意义

标签 c#

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

MyInterface1 does not contain definition for 'MyClass1'

这是正确的,因为 MyClass1MyInterface2 中。 如果我像这样切换接口(interface)的顺序:

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();
        }
    }
}

编辑:将 setter 添加到 MyClass1

最佳答案

修改后问题很明显

你在做:

public partial class MyPresenter :  ParentPresenter<MyInterface1>

所以这意味着您的类继承自:

public abstract class ParentPresenter<TView> : System.IDisposable

TView 是一个 MyInterface1

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

这个:

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

C#不支持,那是多重继承。它只允许用于接口(interface),但不允许用于类(在最初的问题中你实现了两个接口(interface),这是支持的:编辑后你试图从两个类继承,这是不支持的)。

但是你可以这样做:

public interface MyInterface3 : MyInterface1, MyInterface2
{
}

然后你可以这样做:

public partial class MyPresenter : ParentPresenter<MyInterface3>

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

关于c# - 接口(interface)顺序的意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35207607/

相关文章:

c# - 事件处理程序中的功能代码不好的做法?

c# - 创建用于验证的属性并更改参数值

c# - 使用未在 swagger 中公开的 HTTP 内容上传 API 文件

C#、java DataInputStream.readFully() 等效项

c# - 部署到 GAC

c# - 使用 WCF,REST 和 SOAP 肯定应该协调工作吗?

c# - 蛋糕 : Build script progress

c# - 无法将列表保存到 session /ViewBag 变量

c# - DateTime TryParseExact 包含 3 个字母月份的字符串

c# - InvalidCastException 将对象转换为它自己的类型