2010-07-29 106 views
2

我有一個基礎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等沒有類型參數。這特別奇怪,因爲當我要求它實現接口時,它包含了來自兩個相關接口的所有成員。

+0

我幾乎不想這麼說,但示例代碼聞起來很糟糕。我強烈建議你們重新考慮這種方法,因爲它對於你陳述的目的顯得過於複雜。 – NotMe 2010-07-29 15:18:14

回答

1

它看起來像你有一個循環參考 - 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; } 
} 

值得看你是否真的需要所有的通用打字 - 你可能是與非通用底層接口更好,因爲這些會更容易使用的代碼。