0

我想执行如下所示的演员表:

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

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

4

1 回答 1

1

好吧,我的水晶球正在服役。所以我对你想要做什么的猜测是:

  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;
    }


}
于 2013-07-04T13:55:31.783 回答