将对象转换为泛型类型

时间:2013-07-04 09:57:07

标签: c# .net entity-framework reflection

我想表演如下的演员:

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 个答案:

答案 0 :(得分:1)

我的水晶球正在服务中。所以我猜你要做的是:

  1. 动态访问某个属性。
  2. 动态调用泛型方法
  3. 动态调用实例化对象
  4. 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;
        }
    
    
    }