2014-04-14 21 views
1

我有以下通用抽象類:的參考MyClass類<F,T>類型參數的數目不正確 - 通用實體框架

public abstract class MyClass<F, T> 
    where TCurrencyFrom : Book 
    where TCurrencyTo : Book 
{ 
    public int Id { get; set; } 
    public virtual F First{ get; set; } 
    public virtual T Second { get; set; } 
} 

而且我得到了3類,其實現這樣的類:

public class Implementation1 : MyClass<BookType1, BookType2> 
{ 
} 

public class Implementation2 : MyClass<BookType2, BookType1> 
{ 
} 

現在,我得到了一個 「EntityTypeConfiguration」 對於那些看起來像:

public class MyClassConfiguration<TMyClass> : EntityTypeConfiguration<TMyClass> where TMyClass: MyClass 
{ 
    public MyClassConfiguration() 
    { 
     ... 
    } 
} 

並嘗試用這些像:

public class Implementation1Map : MyClassConfiguration<Implementation1> 
{ 
    public Implementation1Map() 
    { 
     ... 
    } 
} 

但後來我得到以下錯誤:

Incorrect number of type parameters in reference class MyClass

我怎樣才能解決這個問題,並確保我對EntityTypeConfigurations一個通用的辦法?

回答

3

不幸的是,對於.NET泛型而言,這很棘手。

如果MyClassConfiguration並不真正關心的類型參數,您可能希望創建一個非通用接口:

public interface IMyClass 
{ 
    // Any members of MyClass<,> which don't rely on the type arguments, 
    // e.g. the Id property 
} 

然後讓MyClass<,>實施IMyClass

// Type parameters renamed to make the type constraints sensible... 
public abstract class MyClass<TCurrencyFrom, TCurrencyTo> : IMyClass 
    where TCurrencyFrom : Book 
    where TCurrencyTo : Book 

和更改類型約束爲MyClassConfiguration

public class MyClassConfiguration<TMyClass> : EntityTypeConfiguration<TMyClass> 
    where TMyClass: IMyClass 

(顯然,你會想給IMyClass一個更有用的名字......)

或者,只是讓MyClassConfiguration一般有三種類型的參數:

public class MyClassConfiguration<TMyClass, TCurrencyFrom, TCurrencyTo> 
    : EntityTypeConfiguration<TMyClass> 
    where TMyClass: MyClass<TCurrencyFrom, TCurrencyTo> 
    where TCurrencyFrom : Book 
    where TCurrencyTo : Book 

public class Implementation1Map 
    : MyClassConfiguration<Implementation1, BookType1, BookType2> 

public class Implementation2Map 
    : MyClassConfiguration<Implementation2, BookType2, BookType1> 

它的醜陋,但它會工作。

+0

那裏TCurrencyFrom:Book 哪裏TCurrencyTo:Book是否正確? –

+0

@ K.B:編輯以顯而易見的方式重命名類型參數。 –

+0

如果沒有界面,這是不可能的?因爲我怎麼看它的界面並沒有真正添加任何東西。它只會被用來「解決」問題。 – Julian

相關問題