Skip to main content
 首页 » 编程设计

c#之引用类 MyClassF,T> 中的类型参数数量不正确之通用 Entity Framework

2024年02月13日10bjzhanghao

我有以下通用抽象类:

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 有一个通用的方法?

请您参考如下方法:

不幸的是,这对于 .NET 泛型来说很棘手。

如果MyClassConfiguration实际上并不关心类型参数,您可能想要创建一个非通用接口(interface):

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> 

这很丑陋,但它会起作用。