gpt4 book ai didi

c# - 如何将通用属性作为参数传递给函数?

转载 作者:太空狗 更新时间:2023-10-29 22:04:24 25 4
gpt4 key购买 nike

我需要编写一个函数来接收一个属性作为参数并执行它的 getter。

如果我需要传递一个函数/委托(delegate),我会使用:

delegate RET FunctionDelegate<T, RET>(T t);

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

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

最佳答案

你也可以这样写:

static void Method<T, U>(this T obj, Expression<Func<T, U>> property)
{
var memberExpression = property.Body as MemberExpression;
//getter
U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null);
//setter
obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null);
}

调用示例:

DbComputerSet cs = new DbComputerSet();
cs.Method<DbComputerSet, string>(set => set.Code);

关于c# - 如何将通用属性作为参数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/110562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com