簡體   English   中英

從Type with Reflection獲取類並使用Type in C#調用泛型構造函數

[英]Get class from Type with Reflection and call a generic constructor with Type in C#

我正在使用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)?>()

我發現這是一個類似的問題 ,但我需要調用泛型構造函數而不是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);
}

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

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

我寫這篇文章沒有智能感知,只是瀏覽了你的代碼,所以請讓我知道我是否犯過任何錯誤,我會糾正它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM