获取属性名称

有没有办法获取传递给函数的值的属性名称?

你在问这是否可行?

public void PrintPropertyName(int value) { Console.WriteLine(someMagicCodeThatPrintsThePropertyName); } // x is SomeClass having a property named SomeNumber PrintInteger(x => x.SomeNumber); 

和“SomeNumber”将打印到控制台?

如果是这样,不。 这显然是不可能的(提示: PrintPropertyName(5)会发生什么?)。 但是你可以这样做:

 public static string GetPropertyName(this Expression> expression) { Contract.Requires(expression != null); Contract.Ensures(Contract.Result() != null); PropertyInfo propertyInfo = GetPropertyInfo(expression); return propertyInfo.Name; } public static PropertyInfo GetPropertyInfo(this Expression> expression) { Contract.Requires(expression != null); Contract.Ensures(Contract.Result() != null); var memberExpression = expression.Body as MemberExpression; Guard.Against(memberExpression == null, "Expression does not represent a member expression."); var propertyInfo = memberExpression.Member as PropertyInfo; Guard.Against(propertyInfo == null, "Expression does not represent a property expression."); Type type = typeof(TSource); Guard.Against(type != propertyInfo.ReflectedType && type.IsSubclassOf(propertyInfo.ReflectedType)); return propertyInfo; } 

用法:

 string s = GetPropertyName((SomeClass x) => x.SomeNumber); Console.WriteLine(s); 

现在“SomeNumber”将打印到控制台。

只有你使用lambda,即

 SomeMethod(()=>someObj.PropName); 

(使用该方法采用类型化表达式树而不仅仅是值)

然而,这仍需要相当多的处理来解决并涉及reflection和表达。 除非绝对必要,我会避免这种情况。 仅仅为此学习表达是不值得的。

不会。在调用函数之前将对属性进行求值,函数中的实际值将是该值的副本 ,而不是属性本身。