好吧,我的水晶球正在服役。所以我对你想要做什么的猜测是:
- 动态访问 aa 属性。
- 动态调用泛型方法
- 动态调用实例化对象
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;
}
}