当属性类型未知时,通过reflection创建属性访问者的委托
在.NET 2.0(使用C#3.0)中,当我在编译时不知道它的类型时,如何为通过reflection获得的属性访问器创建委托?
例如,如果我有int
类型的属性,我可以这样做:
Func getter = (Func)Delegate.CreateDelegate( typeof(Func), this, property.GetGetMethod(true)); Action setter = (Action)Delegate.CreateDelegate( typeof(Action), this, property.GetSetMethod(true));
但如果我不知道该属性在编译时是什么类型,我不知道该怎么做。
你需要的是:
Delegate getter = Delegate.CreateDelegate( typeof(Func<>).MakeGenericType(property.PropertyType), this, property.GetGetMethod(true)); Delegate setter = Delegate.CreateDelegate( typeof(Action<>).MakeGenericType(property.PropertyType), this, property.GetSetMethod(true));
但是,如果你这样做是为了提高性能,你仍然会做空,因为你需要使用动态循环 DynamicInvoke()
。 您可能希望查看元编程以编写一个包含/返回object
的包装器。 或者看看HyperDescriptor为您做到这一点。