//获取一个获取特定属性的值的委托 /// <summary> /// 获取一个获取特定属性的值的委托 /// <para>返回结果: /// </para>一个object ReflectGet(object obj)类型的委托 /// </summary> /// <param name="classType">需要获取属性的类</param> /// <param name="propertyName">属性名称</param> public static ReflectGet GetPropertyValue(Type classType, string propertyName) { string cacheKey = classType.FullName + SPACE + propertyName; //缓存标识符key ReflectGet returnDelegate = null; //声明返回委托对象 if (cacheGet.TryGetValue(cacheKey, out returnDelegate)) //取出缓存中的委托,如果没有返回false { return(returnDelegate); //如果有,直接返回该委托 } ReflectGet reflectGet = null; returnDelegate = delegate(object obj) { return(reflectGet(obj)); }; //给返回委托赋值 cacheGet.Add(cacheKey, returnDelegate); //添加到缓存 PropertyInfo propertyInfo = classType.GetProperty(propertyName, EasyIL.ALLATTR); //获得属性对象PropertyInfo reflectGet = delegate(object obj) //使用系统反射方法 { return(propertyInfo.GetGetMethod().Invoke(obj, null)); }; //开启新线程初始化动态方法 ThreadPool.QueueUserWorkItem(delegate(object o) { //Type returnType = classType.GetProperty(propertyName, EasyIL.ALLATTR).PropertyType; Type returnType = typeof(object); //设置返回值类型 Type argType = typeof(object); //设置参数类型 EasyIL il = new EasyIL(returnType, classType.Module, argType); //建立简单EasyIL对象 //EasyIL:自定义类,用于简单操作IL生成器生成动态方法 //ILParameterBase obj = il.Convert(classType, il["0"]); //将参数0转换为 ILProperty objProperty = il.CreateProperty(propertyInfo, il["0"]); //根据对象和属性对象 创建IL参数 //il[0]表示第0个参数的ILProperty形式,ILProperty:自定义类,用于在EasyIL中代表一个参数 il.Return(objProperty); //return 属性的值 //Type delegateType = typeof(delegateGeneric<,>).MakeGenericType(returnType, classType); reflectGet = (ReflectGet)il.CreateDelegate(typeof(ReflectGet)); //返回一个委托 }); return(returnDelegate); }
//获取一个设置特定属性的值的委托 /// <summary> /// 获取一个设置特定属性的值的委托 /// <para>返回结果: /// </para>一个void ReflectSet(object obj, object value)类型的委托 /// </summary> /// <param name="classType">需要设置属性的类</param> /// <param name="propertyName">属性名称</param> public static ReflectSet SetPropertyValue(Type classType, string propertyName) { ReflectSet returnDelegate; string cacheKey = classType.FullName + SPACE + propertyName; if (cacheSet.TryGetValue(cacheKey, out returnDelegate)) { return(returnDelegate); } ReflectSet reflectSet = null; returnDelegate = delegate(object obj, object value) { reflectSet(obj, value); }; cacheSet.Add(cacheKey, returnDelegate); PropertyInfo propertyInfo = classType.GetProperty(propertyName, EasyIL.ALLATTR); //获得属性对象PropertyInfo reflectSet = delegate(object obj, object value) { propertyInfo.GetSetMethod().Invoke(obj, new object[] { value }); }; ThreadPool.QueueUserWorkItem(delegate(object o) { Type argType = typeof(object); EasyIL il = new EasyIL(null, classType.Module, argType, argType); ILProperty objProperty = il.CreateProperty(propertyInfo, il["0"]); //根据对象和属性对象 创建IL参数 objProperty.SetValue(il["1"].StValue()); il.Return(); reflectSet = (ReflectSet)il.CreateDelegate(typeof(ReflectSet)); }); return(returnDelegate); }