代码之家  ›  专栏  ›  技术社区  ›  Matt

实现通用接口时出现问题

  •  2
  • Matt  · 技术社区  · 16 年前

    在基本dll中,我设置了一系列这样的接口

    public interface IVendor
    {
        string Name { get; set; }    
    }
    
    public interface IVendor<TC> : IVendor where TC : IAccount
    {
        IEnumerable<TC> Accounts { get; set; }
    }
    
    public interface IAccount
    {
        string Name { get; set; }
    }
    
    public interface IAccount<TP, TC> : IAccount where TP : IVendor
                                                 where TC : IExecutionPeriod
    {
        TP Vendor{ get; set; }
        IEnumerable<TC> ExecutionPeriods { get; set; }
    }
    

    这将继续向下扩展到多个层次,所有内容都可以很好地编译。

    当我试图在服务中实现这一点时,问题就出现了。

    public class FirstVendor : IVendor<FirstVendorAccount>
    {
        public string Name { get; set; }
        public IEnumerable<FirstVendorAccount> Accounts { get; set;}
    }
    
    public class FirstVendorAccount : IAccount<FirstVendor, FirstVendorExecutionPeriod>
    {
        public FirstVendor Vendor { get; set; }
        public string Name { get; set; }
        public IEnumerable<FirstVendorExecutionPeriod> ExecutionPeriods { get; set; }
    }
    

    我得到一个编译器错误,IVendor、IAccount等没有类型参数。这特别奇怪,因为当我要求它实现接口时,它包含了来自两个相关接口的所有成员。

    1 回复  |  直到 16 年前
        1
  •  1
  •   Keith    16 年前

    看起来你有一个循环引用- FirstVendorAccount 需要知道 FirstVendor

    使其中一个类成为具有泛型类型的“支配”类,那么另一个可以只返回基接口。

    public interface IVendor
    {
        string Name { get; set; }    
    }
    
    public interface IVendor<TC> : IVendor where TC : IAccount
    {
        IEnumerable<TC> Accounts { get; set; }
    }
    
    public interface IAccount
    {
        string Name { get; set; }
    }
    
    // no longer needs IVendor<TC> before it can be compiled
    public interface IAccount<TC> : IAccount where TC : IExecutionPeriod
    {
        IVendor Vendor{ get; set; }
        IEnumerable<TC> ExecutionPeriods { get; set; }
    }
    

    值得一看的是,您是否真的需要所有的泛型类型——您最好使用非泛型底层接口,因为这些接口将更容易编写代码。