从类类型或字符串中获取类引用

时间:2016-12-12 06:25:15

标签: c# generics reflection

所以我一直在寻找大量类似的问题,但他们似乎都没有尝试过同样的事情。我需要对类的引用,而不是类实例。

我正在尝试为泛型类型函数动态创建类引用。我的功能如下:

private void CleanupTable<T, U>(DbSet<T> dbSet, CleanupModel.Tables table, DbSet<U> lastDbSet, dynamic removedRec) where T : class where U : class
{
    ParameterExpression tpe = Expression.Parameter(typeof(T));
    Expression idProp = Expression.Property(tpe, typeof(T).GetProperty(GetIdProperty(lastDbSet)));
    Expression constIdProp = Expression.Constant(removedRec.GetType().GetProperty(GetIdProperty(lastDbSet)).GetValue(removedRec, null), typeof(int));
    Expression completeExpression = Expression.Equal(idProp, constIdProp);

    Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(completeExpression, tpe);
    List<T> removedRecs = dbSet.Where(expression).ToList();

    removedRecs.ForEach(rec =>
    {
        DbSet nextSet = GetNextSet(dbSet);

        //Here is where I'm trying to create a reference using nextSet
        CleanupTable</*nextSetType reference*/, T>(nextSet, GetNextTable(dbSet), dbSet, rec);

        dbSet.Remove(rec);
        reportHelper.ReportSuccess(table, ReportHelper.ReportReasons.Linked, rec);
    });
}

以下是GetNextSet()的代码:

private DbSet GetNextSet(CleanupModel.Tables table)
{
    switch (table)
    {
        case CleanupModel.Tables.Version: return context.Page;
        //More cases
        default: return null;
    }
}

我尝试使用GetType()之类的内容,但通用版不接受Type。是我试图做的甚至可能吗?

1 个答案:

答案 0 :(得分:0)

所以我在InBetween的帮助下解决了这个问题。我最终让CleanupTable()从参数中推断出类型。最初的问题是它无法推断nextSet的类型,因为它是通用的DbSet类型,并且没有隐式输入。我通过将相关值设置为动态来解决了这个问题,让CleanupTable()在运行时计算出来。

以下是更新的代码:

CleanupTable()

private void CleanupTable<T, U>(DbSet<T> dbSet, CleanupModel.Tables table, DbSet<U> lastDbSet, dynamic removedRec) where T : class where U : class
{
    ParameterExpression tpe = Expression.Parameter(typeof(T));
    Expression idProp = Expression.Property(tpe, typeof(T).GetProperty(GetIdProperty(lastDbSet)));
    Expression constIdProp = Expression.Constant(removedRec.GetType().GetProperty(GetIdProperty(lastDbSet)).GetValue(removedRec, null), typeof(int));
    Expression completeExpression = Expression.Equal(idProp, constIdProp);

    Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(completeExpression, tpe);
    List<T> removedRecs = dbSet.Where(expression).ToList();

    removedRecs.ForEach(rec =>
    {
        dynamic nextSet = GetNextSet(table);
        if (nextSet == null)

        CleanupTable(nextSet, GetNextTable(table), dbSet, rec);

        dbSet.Remove(rec);
        reportHelper.ReportSuccess(table, ReportHelper.ReportReasons.Linked, rec);
    });
}

GetNextSet()

private dynamic GetNextSet(CleanupModel.Tables table)
{
    switch (table)
    {
        case CleanupModel.Tables.Version: return context.Page;
        //More cases

        default: return null;
    }
}