我需要编写一个函数来接收一个属性作为参数并执行它的 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/