问题描述
在.NET 2.0(使用C#3.0)中,当我在编译时不知道其类型时,如何为通过反射获取的属性访问器创建代理?
In .NET 2.0 (with C# 3.0), how can I create a delegate for a property accessor obtained via reflection when I don't know its type at compile time?
例如如果我有类型为 int
的财产,我可以这样做:
E.g. if I have property of type int
, I can do this:
Func<int> getter = (Func<int>)Delegate.CreateDelegate(
typeof(Func<int>),
this, property.GetGetMethod(true));
Action<int> setter = (Action<int>)Delegate.CreateDelegate(
typeof(Action<int>),
this, property.GetSetMethod(true));
但是如果我不知道在编译时的属性是什么类型,我不知道
but if I do not know what type the property is at compile time, I don't know how to do it.
推荐答案
您需要的是:
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()
,这是 slooow 。您可能想要查看元编程来编写一个包含/取回对象
的包装器。或者看看HyperDescriptor,为你做这个。
however, if you are doing this for performance, you are still going to come up short, since you would need to use DynamicInvoke()
, which is slooow. You might want to look at meta-programming to write a wrapper that takes/returns object
. Or look at HyperDescriptor which does this for you.
这篇关于当属性类型未知时,通过反射创建属性acctor的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!