动态地为通用方法提供type参数

时间:2018-01-02 16:29:48

标签: c# generics type-parameter

我正在开发一个从csv / xml文件导入数据并将所选数据存储在SQL数据库中的项目。 我遇到了一个问题,我不得不使用类型参数调用某些泛型方法,这些方法依赖于我并且不想编写每个可能的情况。

有没有办法以可变方式传递type参数?

我已经以一种黑客的方式解决了这个问题。我很好奇是否有推荐的方式,因为这是常见的情况。

编辑: 我的方法看起来像这样:

我已经生成了一个Func<dynamic>,它返回某个实体的新实例,并将它们与实体名称一起存储在Dictionary中。

我想以上述方式调用的每个泛型方法都获得了泛型类型的参数。这样编译器就可以找出类型而无需显式编写。唯一的缺点是我每次都必须传递一个假人。

public abstract class Entity
{
    private static readonly Dictionary<string, Func<dynamic>> instantiateNewTypedEntityDelegatesDict;

    static Entity()
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        instantiateNewTypedEntityDelegatesDict = new Dictionary<string, Func<dynamic>>();
        foreach (var entityType in assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Entity))))
        {
            CreateInstantiateNewTypedEntityDelegate(entityType);
        }
    }

    private static void CreateInstantiateNewTypedEntityDelegate(Type entityType)
    {
        NewExpression newExpr = Expression.New(entityType.GetConstructor(new Type[0]) ?? throw new InvalidOperationException());
        instantiateNewTypedEntityDelegatesDict.Add(entityType.Name, Expression.Lambda<Func<dynamic>>(newExpr).Compile());
    }

    public static dynamic CreateNewTypedEntity(string entityName)
    {
        return instantiateNewTypedEntityDelegatesDict[entityName]();
    }
}

我要调用的方法的示例原型:

public TEntity GenericMethodIWantToCall<TEntity>(TEntity dummyEntity /*other paramters do not matter*/)

0 个答案:

没有答案
相关问题