2011-08-30 15 views
3

在.NET 2.0(与C#3.0),我怎么能创建一个属性访问器通过反射获得委托,当我不知道它的类型在编译时?当财产类型未知时,通过反射获得属性的代理创建委托

例如如果我有int类型的财产,我可以这样做:

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)); 

,但如果我不知道物业是在编译时什么类型的,我不知道该怎么做。

+1

不知道,但这下面的问题看起来有关:http://stackoverflow.com/questions/773099/generating-delegate-types-dynamically-in-c – Till

+0

'功能'是.NET 3.5 ....是这是一个自定义的'Func '? –

+0

@Marc Gravell - Whoops实际上是在一个针对错误平台的临时项目中玩耍,但它可以在.NET 2.0中使用自定义的Func 。 – Ergwun

回答

2

你需要的是:

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。您可能希望查看元编程来编写一个包含/返回object的包装。或者看看HyperDescriptor是否为你做到这一点。

+0

关于http://stackoverflow.com/questions/2490828/createdelegate-with-unknown-types? – Till

+0

@Till如果你的意思是接受的答案......如果你事先不知道类型,你将不得不使用'MakeGenericMethod()';然后它使用反射创建一个委托立即使用一次并放弃。坦率地说,在那个例子中,原始反射('GetValue()'/'SetValue()')会更好。 –

+0

@马克砾石 - 是的,正在努力做到这一点。当我有更多时间时,我会查看HyperDescriptor - 看起来很棒。 – Ergwun

相关问题