我正在使用Reflection.Emit
动态生成属性的吸气剂。到目前为止,我的代码在我测试过的所有情况下都有效,除非该属性不是公共的,或者是具有私有访问器的公共属性。通过迭代 GetProperties 的结果传入 PropertyInfo。当属性不公开时,调用delegate
throws
"System.NullReferenceException : Object reference not set to an instance of an object."
我正在使用此代码生成: ( property
is a PropertyInfo
)
// Get setter or return null
MethodInfo setMethod = property.GetSetMethod ();
if (setMethod == null)
return null;
// Method names follow the pattern: "_Set<Property>_"
DynamicMethod dm = new DynamicMethod(String.Concat ("_Set", property.Name, "_"), typeof(void),
new Type[] { typeof(object), typeof(object) },
property.DeclaringType, true);
ILGenerator generator = dm.GetILGenerator ();
generator.Emit (OpCodes.Ldarg_0);
generator.Emit (OpCodes.Castclass, property.DeclaringType);
generator.Emit (OpCodes.Ldarg_1);
if (property.PropertyType.IsClass)
generator.Emit (OpCodes.Castclass, property.PropertyType);
else
generator.Emit (OpCodes.Unbox_Any, property.PropertyType);
generator.EmitCall (OpCodes.Callvirt, setMethod, null);
generator.Emit (OpCodes.Ret);
return (Action<object, object>)dm.CreateDelegate (typeof(Action<object, object>));