簡體   English   中英

在C#中使用Lambda表達式獲取對象屬性為字符串

[英]Getting Object Property to String Using Lambda Expression in C#

假設我有這個課:

class MyClass {
  public int MyProperty { get; set; }
}

我想以字符串形式(例如“ MyProperty”)獲取MyProperty,但要通過lambda表達式或“重構友好”的任何其他方式。

是否有這樣的語法:

void BindToDataSource(IEnumerable<MyClass> list) {
    myComboBox.DataSource = list;
    myComboBox.DisplayMember = typeof(MyClass).GetPropertyToString(c => c.MyProperty);
}

我不想這段代碼:

myComboBox.DisplayMember = "MyProperty"

因為它不是“重構友好”的。

看看這個問題的答案: C#中缺乏用於類型安全數據綁定的'nameof'運算符的解決方法?

就您而言,如果您實現此泛型類:

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;
    }
}

您可以像這樣使用它:

void BindToDataSource(IEnumerable<MyClass> list) 
{
    myComboBox.DataSource = list;
    myComboBox.DisplayMember = Nameof<MyClass>.Property(e => e.MyProperty);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM