如何添加此方法扩展方法到我的类的属性? [英] How can I add this method as an extension method to properties of my class?
问题描述
我有一个方法,我想添加这个方法扩展方法我类的属性。
该方法给出一个表达式作为输入参数。该方法是象下面这样:
I have a method and I want to add this method as an extension method to properties of my class. This method give an expression as input parameter. The method is like below :
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
我想用这个方法就像下面的例子:
I want to use this method like below example :
string propertyName = MyClass.Property1.GetPropertyName();
这可能吗?如果是,该如何解决?
Is it possible? if yes, what is the solution?
推荐答案
没有,这是不可能做到这一点。目前尚不清楚是否 MyClass的
是一个类的名称( Property1
是一个静态属性)还是它的一个实例财产和 MyClass.Property1
根本就不是一个有效的成员访问。如果是后者,你可能想改变你的方法是这样的:
No, it's not possible to do that. It's not clear whether MyClass
is the name of a class (and Property1
is a static property) or whether it's an instance property and MyClass.Property1
simply isn't a valid member access. If it's the latter, you probably want to change your method to something like:
public static string GetPropertyName<TSource, TResult>(
Expression<Func<TSource, TResult>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
和称呼其为:
string propertyName = GetPropertyName<MyClass, string>(x => x.Property1);
或者你的可能的使用通用类与通用的方法,使字符串
可以推断出:
Or you could use a generic class with a generic method, so that string
can be inferred:
string propertyName = PropertyUtil<MyClass>.GetPropertyName(x => x.Property1);
这会是这样的:
public static class PropertyUtil<TSource>
{
public static string GetPropertyName<TResult>(
Expression<Func<TSource, TResult>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
}
这篇关于如何添加此方法扩展方法到我的类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!