繁体   English   中英

将对象转换为通用类型

[英]Cast an object into a generic type

我想像下面这样进行演员转换:

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. 动态访问aa属性。
  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;
    }


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM