引用类MyClass <f,t>中的类型参数数量不正确 - 通用实体框架</f,t>

时间:2014-04-14 08:58:59

标签: c# entity-framework generics

我有以下通用抽象类:

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 ()
    {
        ...
    }
}

但后来我收到以下错误:

  

引用类MyClass

中的类型参数数量不正确

如何解决此问题并确保我对EntityTypeConfigurations采用通用方法?

1 个答案:

答案 0 :(得分:4)

不幸的是,使用.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>

这很难看,但它会起作用。