Tag: setvalue

PropertyInfo实例上的SetValue错误“对象与目标类型不匹配”c#

在以前的项目中的各个地方使用带有此代码的Copy方法(处理具有相同命名属性但不从公共基类派生或实现公共接口的对象)。 新的工作场所,新的代码库 – 现在它在SetValue失败,“对象与目标类型不匹配”,即使是非常简单的例子……它上周工作了…. public static void Copy(object fromObj, object toObj) { Type fromObjectType = fromObj.GetType(); Type toObjectType = toObj.GetType(); foreach (System.Reflection.PropertyInfo fromProperty in fromObjectType.GetProperties()) { if (fromProperty.CanRead) { string propertyName = fromProperty.Name; Type propertyType = fromProperty.PropertyType; System.Reflection.PropertyInfo toProperty = toObjectType.GetProperty(propertyName); Type toPropertyType = toProperty.PropertyType; if (toProperty != null && toProperty.CanWrite) { object fromValue = […]

有没有办法创建一个委托来获取和设置FieldInfo的值?

对于属性,有GetGetMethod和GetSetMethod以便我可以这样做: Getter = (Func)Delegate.CreateDelegate(typeof(Func), propertyInfo.GetGetMethod()); 和 Setter = (Action)Delegate.CreateDelegate(typeof(Action), propertyInfo.GetSetMethod()); 但是我该如何处理FieldInfo ? 我不是在寻找GetValue和SetValue代表(这意味着我每次都会调用reflection) Getter = s => (T)fieldInfo.GetValue(s); Setter = (s, t) => (T)fieldInfo.SetValue(s, t); 但是如果这里有CreateDelegate方法吗? 我的意思是, 因为赋值返回一个值 ,我可以将赋值视为一种方法吗? 如果有的话,它有一个MethodInfo句柄吗? 换句话说,我如何传递正确的MethodInfo设置并从成员字段获取值到CreateDelegate方法,以便我得到一个委托,我可以直接读取和写入字段? Getter = (Func)Delegate.CreateDelegate(typeof(Func), fieldInfo.??); Setter = (Action)Delegate.CreateDelegate(typeof(Action), fieldInfo.??); 我可以构建表达式并编译它,但我正在寻找更简单的东西。 最后,如果问题没有答案,我不介意去表达路线 ,如下所示: var instExp = Expression.Parameter(typeof(S)); var fieldExp = Expression.Field(instExp, fieldInfo); Getter = Expression.Lambda<Func>(fieldExp, instExp).Compile(); […]

reflection性能 – 创建代理(属性C#)

我在使用reflection时遇到了性能问题。 所以我决定为我的对象的属性创建委托,到目前为止得到了这个: TestClass cwp = new TestClass(); var propertyInt = typeof(TestClass).GetProperties().Single(obj => obj.Name == “AnyValue”); var access = BuildGetAccessor(propertyInt.GetGetMethod()); var result = access(cwp); static Func BuildGetAccessor(MethodInfo method) { var obj = Expression.Parameter(typeof(object), “o”); Expression<Func> expr = Expression.Lambda<Func>( Expression.Convert( Expression.Call( Expression.Convert(obj, method.DeclaringType), method), typeof(object)), obj); return expr.Compile(); } 结果非常令人满意,比使用传统方法快3-40-40倍( PropertyInfo.GetValue (obj, null); ) 问题是: 如何制作属性的SetValue ,其工作方式相同? […]