java泛型作文参数传递,如何将泛型属性作为参数传递给函数?

I need to write a function that receives a property as a parameter and execute its getter.

If I needed to pass a function/delegate I would have used:

delegate RET FunctionDelegate(T t);

void func(FunctionDelegate function, T param, ...)

{

...

return function.Invoke(param);

}

Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?

解决方案

You can use reflection, you can get a MethodInfo object for the get/set accessors and call it's Invoke method.

The code example assumes you have both a get and set accessors and you really have to add error handling if you want to use this in production code:

For example to get the value of property Foo of object obj you can write:

value = obj.GetType().GetProperty("Foo").GetAccessors()[0].Invoke(obj,null);

to set it:

obj.GetType().GetProperty("Foo").GetAccessors()[1].Invoke(obj,new object[]{value});

So you can pass obj.GetType().GetProperty("Foo").GetAccessors()[0] to your method and execute it's Invoke method.

an easier way is to use anonymous methods (this will work in .net 2.0 or later), let's use a slightly modified version of your code example:

delegate RET FunctionDelegate(T t);

void func(FunctionDelegate function, T param, ...)

{

...

return function(param);

}

for a property named Foo of type int that is part of a class SomeClass:

SomeClass obj = new SomeClass();

func(delegate(SomeClass o){return o.Foo;},obj);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值