2010-11-04 233 views

回答

5

你问这是否可能?

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<TSource, TProperty>(this Expression<Func<TSource, TProperty>> expression) { 
    Contract.Requires<ArgumentNullException>(expression != null); 
    Contract.Ensures(Contract.Result<string>() != null); 
    PropertyInfo propertyInfo = GetPropertyInfo(expression); 
    return propertyInfo.Name; 
} 

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

用法:

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

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

2

号的物业进行评估函数被调用之前,并且在功能的实际值将是值的副本,而不是物业本身。

5

只有当您使用拉姆达时,即,

SomeMethod(()=>someObj.PropName); 

(一个具有该方法采取一个输入表达式树,而不是仅仅一个值的)

然而,这仍需要相当多的处理来解决,并涉及反射和表达。除非绝对必要,否则我会避免这样做只为了这个,不值得学习表达。

+0

@Adeel不要这么快就编辑。给这个人一个机会去编辑他自己的东西!我认为等待五分钟是恭敬的。 – 2010-11-04 17:17:32

+0

@Josh - 我不介意;我在iPod上,所以我不会注意到,除非他编辑 – 2010-11-04 17:18:23

+0

@Josh是的,我会照顾它。感谢您的建议。 – Adeel 2010-11-04 17:19:07