简体   繁体   English

确定泛型类是否实现类型

[英]Determine if Generic Class Implements Type

I'm working on a sharp-architecture project that mixes fluent mappings and auto mappings. 我正在一个将流利的映射和自动映射混合在一起的尖锐的体系结构项目。 A basic sharp-architecture project already has a method (AutoMappingConfiguration.ShouldMap) that determines if a type should be automatically mapped or not. 一个基本的尖锐体系结构项目已经具有一种方法(AutoMappingConfiguration.ShouldMap),该方法确定是否应自动映射类型。 Mine currently looks like this: 我的当前看起来像这样:

    public override bool ShouldMap(System.Type type)
    {
        if (type == typeof(ActiveUser))
            return false;

        return type.GetInterfaces().Any(x =>
             x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
    }

Essentially the type ActiveUser is mapped using a fluent mapping and everything else is mapped using auto mapping, except for the generic base classes of course. 本质上,ActiveUser类型是使用流畅的映射来映射的,其他所有内容都是使用自动映射来映射的,当然,除了通用基类。 I'm at the point where I will be adding more fluently mapped classes and really don't want to keep adding if statements to this method to exclude them. 我现在要添加更流畅的映射类,并且真的不想继续在此方法中添加if语句以排除它们。 I basically need the method 我基本上需要方法

bool ShouldMap(System.Type type)

to return true if the generic class 如果泛型类返回true

ClassMap<type> 

exists. 存在。

Any suggestions? 有什么建议么?

You can create the generic type using Type.MakeGenericType so assuming you have an assembly which contains all the mappings you can do: 您可以使用Type.MakeGenericType创建泛型类型,因此假设您有一个包含所有可以执行的映射的程序集:

public bool ShouldMap(Assembly mappingAssembly, Type type)
{
    Type classMapType = typeof(ClassMap<>).MakeGenericType(type);
    return mappingAssembly.GetTypes().Any(t => t.IsSubclassOf(classMapType));
}

您是否考虑过映射所有类,但是对要显式映射的类(而不是常规的流利映射)使用Mapping * Override *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM