[英]Get the name of a property by passing it to a method
StackOverflow user jolson had a very nice piece of code that exemplifies how one can register menthods without using strings, but expression trees here . StackOverflow用户jolson有一段很好的代码,它举例说明了如何在不使用字符串的情况下注册menthods,而是在这里表达树。
Is it possible to have something similar for properties instead of methods? 是否可以为属性而不是方法提供类似的东西? To pass a property (not the name of the property) and inside the method to obtain the property name? 传递属性(不是属性的名称)并在方法内部获取属性名称?
Something like this: 像这样的东西:
RegisterMethod(p => p.Name)
void RegisterMethod(Expression??? propertyExpression) where T : Property ???
{
string propName = propertyExpression.Name;
}
Thanks. 谢谢。
I posted a full example of this here (see also the post about " this
" underneath it) 我在这里发布了一个完整的例子(另见下面有关“ this
”的帖子)
Note it deals with the LambdaExpression
etc. As an update to the code as posted, you can add a bit more to make it easier to use in some scenarios: 请注意,它处理LambdaExpression
等。作为已发布代码的更新,您可以添加更多内容,以便在某些情况下更容易使用:
static class MemberUtil<TType>
{
public static string MemberName<TResult>(Expression<Func<TType, TResult>> member)
{
return MemberUtil.MemberName<TType, TResult>(member);
}
}
Then you can use generic type-inference for the return value: 然后,您可以使用泛型类型推断作为返回值:
string test1 = MemberUtil<Foo>.MemberName(x => x.Bar);
string test2 = MemberUtil<Foo>.MemberName(x => x.Bloop());
You can write something along this: 你可以写这个:
static void RegisterMethod<TSelf, TProp> (Expression<Func<TSelf, TProp>> expression)
{
var member_expression = expression.Body as MemberExpression;
if (member_expression == null)
return;
var member = member_expression.Member;
if (member.MemberType != MemberTypes.Property)
return;
var property = member as PropertyInfo;
var name = property.Name;
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.