键入参数约束违例

时间:2017-03-07 01:15:07

标签: c# generics

我有两个泛型类,在两个不同的程序集中定义,一个派生自另一个。父对类型参数有几个通用约束:

public abstract class CountyBulkImporter<TImport, TContext, TUser>
    : DatabaseBulkImporter<TImport, TContext, TUser>
    where TImport  : class
    where TContext : IdentityDbContext<TUser>, ICampaignContext
    where TUser    : IdentityUser

派生类具有看似相应的约束,但需要注意的是明确指定了一个通用参数(HistoricalBallotInfoTImport):

public class BallotBulkImporter<TContext, TUser> 
    : CountyBulkImporter<HistoricalBallotInfo, TContext, TUser>
    where TContext : IdentityDbContext<TUser>, ICampaignContext
    where TUser    : IdentityUser

仅供参考,ICampaignContext约束在第三个单独的程序集中定义。

我在运行时扫描派生类(它是动态加载的,以便为包含它的程序提供可扩展性):

var junk = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany( x => x.GetTypes() )
    .ToList();

扫描会触发ReflectionTypeLoadException:

  

GenericArguments [1],'TContext',on   'Olbert.WebJobs.CountyBulkImporter`3 [TImport,TContext,TUser]'违反   类型参数'TContext'的约束。

1 个答案:

答案 0 :(得分:0)

事实证明问题是支持程序集没有加载到应用程序中(回想一下,上下文的一部分是我在运行时动态加载程序集以提供可扩展性)。

设置对缺少的支持程序集的引用使其包含在应用程序的bin目录中,该目录使其在运行时可用。

我会把这个粉笔写成一个不起眼的错误信息。需要注意的是,如果您获得了通用的Type参数违规错误,并且正在动态加载程序集,请确保您正在加载动态加载的程序集所需的所有支持程序集。