简体   繁体   English

在C#中使用Lambda表达式获取对象属性为字符串

[英]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.

相关问题 在字典上使用 Lambda 表达式<string, list<object> > 在 C#</string,> - Using a Lambda Expression Over a Dictionary<string, List<object>> in C# Lambda表达式访问对象的属性,该对象是c#中另一个对象的属性 - Lambda expression to access a property of an object that is property of another object in c# C#:有没有办法使用lambda表达式设置集合中对象的属性? - C#: is there a way to set a property of objects in a collection using lambda expression? 使用字符串数组列表C#lambda表达式过滤对象列表 - Filter Object List with string array list C# lambda expression C#要从IEnumerable中删除元素 <Dictionary<string, object> &gt;基于使用lambda表达式的条件? - C# Want to remove elements from IEnumerable<Dictionary<string, object>> based on condition using lambda expression? c#编译Lambda表达式以访问对象的属性(该对象是另一个对象的属性)引发异常 - c# compiled Lambda Expression to access a property of an object that is property of another object throws Exception 使用Lambda表达式(C#)返回对象属性的值 - Return the values of an object's properties using lambda expression (C#) C#在lambda表达式中使用动态字符串或查询 - C# Using Dynamic string or query in lambda expression C#清单 <class> 使用lambda表达式将前3个项目字符串化 - C# List<class> first 3 items to string using lambda expression 在C#中使用string.format生成按子句的lambda表达式? - Generate lambda Expression By Clause using string.format in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM