mas*_*ani 4 c# extension-methods expression properties
我有一个方法,我想将此方法作为扩展方法添加到我的类的属性.此方法将表达式作为输入参数.方法如下:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
我想像下面的例子一样使用这个方法:
string propertyName = MyClass.Property1.GetPropertyName();
Run Code Online (Sandbox Code Playgroud)
可能吗?如果是的话,解决方案是什么?
不,这是不可能的.目前尚不清楚是否MyClass是类的名称(并且Property1是静态属性),或者它是否是实例属性,并且MyClass.Property1不是有效的成员访问权限.如果是后者,您可能希望将方法更改为:
public static string GetPropertyName<TSource, TResult>(
Expression<Func<TSource, TResult>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
string propertyName = GetPropertyName<MyClass, string>(x => x.Property1);
Run Code Online (Sandbox Code Playgroud)
或者您可以使用泛型类和泛型方法,因此string可以推断:
string propertyName = PropertyUtil<MyClass>.GetPropertyName(x => x.Property1);
Run Code Online (Sandbox Code Playgroud)
这将是这样的:
public static class PropertyUtil<TSource>
{
public static string GetPropertyName<TResult>(
Expression<Func<TSource, TResult>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
}
Run Code Online (Sandbox Code Playgroud)