[英]Getting Object Property to String Using Lambda Expression in C#
Suppose I have this class: 假设我有这个课:
class MyClass {
public int MyProperty { get; set; }
}
And I want to get the MyProperty as string (eg "MyProperty") but through lambda expression or any other way that is "refactoring-friendly". 我想以字符串形式(例如“ MyProperty”)获取MyProperty,但要通过lambda表达式或“重构友好”的任何其他方式。
Is there a syntax that is something like this: 是否有这样的语法:
void BindToDataSource(IEnumerable<MyClass> list) {
myComboBox.DataSource = list;
myComboBox.DisplayMember = typeof(MyClass).GetPropertyToString(c => c.MyProperty);
}
I dont want to this code: 我不想这段代码:
myComboBox.DisplayMember = "MyProperty"
because it is not "refactoring-friendly". 因为它不是“重构友好”的。
Take a look at the answer to this: Workaround for lack of 'nameof' operator in C# for type-safe databinding? 看看这个问题的答案: C#中缺乏用于类型安全数据绑定的'nameof'运算符的解决方法?
In your case, if you implement this Generic Class: 就您而言,如果您实现此泛型类:
public class Nameof<T>
{
public static string Property<TProp>(Expression<Func<T, TProp>> expression)
{
var body = expression.Body as MemberExpression;
if(body == null)
throw new ArgumentException("'expression' should be a member expression");
return body.Member.Name;
}
}
You can use it like this: 您可以像这样使用它:
void BindToDataSource(IEnumerable<MyClass> list)
{
myComboBox.DataSource = list;
myComboBox.DisplayMember = Nameof<MyClass>.Property(e => e.MyProperty);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.