将对象强制转换为泛型类型



我想执行如下的转换:

if (prop.PropertyType.GetGenericTypeDefinition() == typeof(ObjectSet<>))
       {
         if (prop.Name.StartsWith("NV_"))
           {
             var nvLookupTable = (prop.GetValue(context) as ObjectSet<>);
             // I know the above statement is wrong. I'd like to cast
             // it as an ObjectSet<NV_Something> where NV_Something is the name
             // of the database table

我每隔几年/几个月/几周就会忘记这些事情,尤其是当我有压力的时候。

好吧,我的水晶球要服役了。所以我猜你想做的是:

  1. 动态访问属性
  2. 动态调用泛型方法
  3. 动态调用实例化对象

1)

dynamic dObj = bla;
dObj.Prop

2) 动态通用方法

 // example looks close to yout issue, (checking removed for brevity) 
 // call method GetRespository<poco>  dynamically on any object that implements ILuw
 // the result passed back is also dynamic.  For obvious reasons.    
 public static dynamic GetDynamicRepository(ILuw iLuw, string pocoFullName)  {
        //null checks removed for demo....
        var pocoType = Type.GetType(pocoFullName);
        MethodInfo method = typeof(ILuw).GetMethod("GetRepository");
        MethodInfo generic = method.MakeGenericMethod(pocoType);
        var IRepOfT = generic.Invoke(iLuw, null);
        dynamic repOfT = IRepOfT;
        return repOfT;
    }

3) 动态通用实例创建,例如存储库实例化

public class RepositoryFactory<TPoco> where TPoco : BaseObjectConstraintHere {
    public IRepositoryBase<TPoco> GetRepository(DbContext context) {
       // get the Pocotype for generic repository instantiation
        var pocoTypes = new[] {typeof (TPoco)};  // but you can also extend to  <T,U>
        Type repBaseType = GetRepositoryType(typeof(TPoco)); // get the best matching Class type
        // now make one of those please..
        IRepositoryBase<TPoco> repository = InstantiateRepository(context, repBaseType, pocoTypes);
       return repository;
    }

    private Type GetRepositoryType(Type T) { 
        if (ConditionX) {
            return typeof(RepositoryX<>);
        }
        return typeof (RepositoryY<>);
    }  // note you can return Repository<,>   if the type requires 2 generic params

    // Now instantiate Class Type with the Generic type passing in a constructor param  
    private IRepositoryBase<TPoco> InstantiateRepository(BosBaseDbContext context, Type repType, params Type[] pocoTypes) {
        Type repGenericType = repType.MakeGenericType(pocoTypes);
        object repInstance = Activator.CreateInstance(repGenericType, context);
        return (IRepositoryBase<TPoco>)repInstance;
    }

}

相关内容

  • 没有找到相关文章

最新更新