[英]Problem implementing generic interface
我有一个基本的DLL,它为我们业务中的关键概念定义了一些基本结构和操作。 然后,该dll包含在每个供应商的特定Web服务中,这些服务实现了与该供应商进行交互的特定业务规则。 (虽然基本概念相同,但实现方式却有很大不同,并且可以独立更改。)
在基本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等没有类型参数。 这特别奇怪,因为当我要求它实现接口时,它包括两个相关接口的所有成员。
看来您有一个循环引用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; }
}
值得一看的是,是否真的需要所有通用类型-使用非通用基础接口可能会更好,因为使用它们将更容易编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.