从Type with Reflection获取类并使用Type in C#调用泛型构造函数

时间:2014-01-21 17:04:36

标签: c# generics reflection types dapper

我正在使用Dapper,我希望遍历我的模型类,并为任何具有ColumnAttribute装饰字段的类设置类型映射。

public class ColumnAttributeTypeMapper<T> : FallbackTypeMapper
{
    public static readonly string ColumnAttributeName = "ColumnAttribute";

    public ColumnAttributeTypeMapper()
        : base(new SqlMapper.ITypeMap[]
        {
            new CustomPropertyTypeMap(typeof (T), SelectProperty),
            new DefaultTypeMap(typeof (T))
        })
    {
    }
    // implementation of SelectProperty and so on...
    // If required, full implementation is on https://gist.github.com/senjacob/8539127
}

在我的模型类库中,我正在迭代所有可能的类型;现在我需要使用类型的类调用泛型ColumnAttributeTypeMapper<T>构造函数。

using System.Web;
using Dapper;

[assembly : PreApplicationStartMethod(typeof(Model.Initiator), "RegisterTypeMaps")]

namespace Model
{
    class Initiator
    {
        public static void RegisterTypeMaps()
        {
            var mappedTypes = Assembly.GetAssembly(typeof (Initiator)).GetTypes().Where(
                f =>
                f.GetProperties().Any(
                    p =>
                    p.GetCustomAttributes(false).Any(
                        a => a.GetType().Name == ColumnAttributeTypeMapper<dynamic>.ColumnAttributeName)));

            // I want to skip registering each class manually :P
            // SqlMapper.SetTypeMap(typeof(Model1), new ColumnAttributeTypeMapper<Model1>());
            // SqlMapper.SetTypeMap(typeof(Model2), new ColumnAttributeTypeMapper<Model2>());

            foreach (var mappedType in mappedTypes)
            {
                SqlMapper.SetTypeMap(mappedType, new ColumnAttributeTypeMapper<mappedType>());
            }
        }
    }
}

如何将类从类型而不是'mappedType'类型传递给new ColumnAttributeTypeMapper<classof(mappedType)?>()

我找到了this as a similar question,但我需要调用泛型构造函数而不是Type的泛型方法。

如果无法完成,请解释一下原因吗?

答案

这就是Tom建议的映射工作方式。

var mapper = typeof(ColumnAttributeTypeMapper<>);
foreach (var mappedType in mappedTypes)
{
    var genericType = mapper.MakeGenericType(new[] { mappedType });
    SqlMapper.SetTypeMap(mappedType, Activator.CreateInstance(genericType) as SqlMapper.ITypeMap);
}

1 个答案:

答案 0 :(得分:3)

您需要方法Type.MakeGenericType;用法如下:

var columnType = typeof(ColumnAttributeTypeMapper<>);
var genericColumn = columnType.MakeGenericType(new[] {typeof(mappedType)});
var instance = Activator.CreateInstance(genericColumn);

我在没有intellisense的情况下写这篇文章,只是浏览了你的代码,所以请告诉我是否犯了错误,我会纠正错误。