如何将泛型属性作为参数传递给函数? [英] How to pass a generic property as a parameter to a function?

查看:762
本文介绍了如何将泛型属性作为参数传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我需要传递一个我曾经使用的函数/委托,那么我需要写一个函数来接收一个属性作为参数并执行它的getter。

 委托RET FunctionDelegate< T,RET>(T t); 

func< T,RET>(FunctionDelegate函数,T param,...)
{
...
return function.Invoke(param);





$ b

是否有类似的方法来定义一个属性,以便我可以调用它的getter和/或setter中的函数代码?

解决方案

您可以使用反射,您可以获取get / set的MethodInfo对象



该代码示例假设您同时拥有get和set访问器,如果要在生产环境中使用它,则必须添加错误处理代码:

例如,要获取object obj的属性Foo的值,您可以编写:

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

来设定它:

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

所以你可以通过obj.GetType()。GetProperty(Foo)。GetAccessors()[ 0]到你的方法并执行它的Invoke方法。

更简单的方法是使用匿名方法(这将在.net 2.0或更高版本中工作),让我们稍微使用代码示例的修改版本:

 委托RET FunctionDelegate< T,RET>(T t); 
$ b void func< T,RET>(FunctionDelegate< T,RET> function,T param,...)
{
...
return function PARAM);
}

获取类型为int的属性,它是类SomeClass的一部分:

  SomeClass obj = new SomeClass(); 
func< SomeClass,int>(Delegate(SomeClass o){return o.Foo;},obj);


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, RET>(T t);

void func<T, RET>(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, RET>(T t);

void func<T, RET>(FunctionDelegate<T,RET> 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<SomeClass,int>(delegate(SomeClass o){return o.Foo;},obj);

这篇关于如何将泛型属性作为参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆