I have got this class:
class foo
{
int val;
public int Val
{
set{ val = values; },
set{ val = values; }
}
}
I need to pass the property name to a DataBinding:
String propertyName = "Val";
ctrl.DataBindings.Add(propertyName, object, dataMember, true, DataSourceUpdateMode.Never);
I want to do something like this:
propertyName = typeof(foo).methods.Val.toString();
If you can use C#6, you have the nameof
operator, which does just that.
string propertyName = nameof(foo.Val);
If you use C# 5, you can leverage expression trees:
public static string GetPropertyName<TParent>(Expression<Func<TParent, object>> prop)
{
var expr = prop.Body;
if (expr.NodeType == ExpressionType.Convert)
expr = ((UnaryExpression)expr).Operand;
if (expr.NodeType == ExpressionType.MemberAccess)
return ((MemberExpression)expr).Member.Name;
throw new ArgumentException("Invalid lambda", "prop");
}
Use this helper function like this (assuming it's in a ReflectionHelper
class):
string propertyName = ReflectionHelper.GetPropertyName<foo>(x => x.Val);
This way, you can safely use refactorings in your IDE.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句