2009-09-13 126 views
1

我寫了一些實用程序類,但如何獲得名稱?可以發送參數名稱爲Mehod不使用object.Name?如何獲取屬性來自對象參數的名稱?

class AutoConfig_Control { 
      public List<string> ls; 
      public AutoConfig_Control(List<string> lv) 
      { 
       ls = lv; 
      } 
      public void Add(object t) 
      { 
       //t.Name; << How to do this 
       //Howto Get t.Name in forms? 

       ls.Add(t.ToString()); 
      } 
     } 
     class AutoConfig 
     { 
      List<string> ls = new List<string>(); 
      public string FileConfig 
      { 
       set; 
       get; 
      } 

      public AutoConfig_Control Config 
      { 
       get { 
        AutoConfig_Control ac = new AutoConfig_Control(ls); 
        ls = ac.ls; 
        return ac; 
       } 
       //get; 
      } 

      public string SaveConfig(object t) { 
       return ls[0].ToString(); 
      } 
     } 

示例使用。

AutoConfig.AutoConfig ac = new AutoConfig.AutoConfig(); 
    ac.Config.Add(checkBox1.Checked); 
    MessageBox.Show(ac.SaveConfig(checkBox1.Checked)); 

回答

2

我知道的唯一途徑是這樣一個黑客:

/// <summary> 
    /// Gets the name of a property without having to write it as string into the code. 
    /// </summary> 
    /// <param name="instance">The instance.</param> 
    /// <param name="expr">An expression like "x => x.Property"</param> 
    /// <returns>The name of the property as string.</returns> 
    public static string GetPropertyName<T, TProperty>(this T instance, Expression<Func<T, TProperty>> expr) 
     { 
      var memberExpression = expr.Body as MemberExpression; 
      return memberExpression != null 
       ? memberExpression.Member.Name 
       : String.Empty; 
     } 

如果你把它放在一個靜態類,你會得到擴展方法GetPropertyName。

然後你就可以在你的例子使用它像

checkbox1.GetPropertyName(cb => cb.Checked) 
+0

我可以使用ac.Config.Add(checkBox1.Checked);同樣,但checkBox1.Name – 2009-09-13 10:34:02

1

完成Rauhotz答案: Expression.Body可能是UnaryExpression(例如用於布爾屬性) 這裏是你應該做的事情與這些樣的工作表達式:

var memberExpression =(expression.Body is UnaryExpression? expression.Body.Operand :expression.Body) as MemberExpression; 
+0

也許我們可以在這裏開發一個通用的GetMemberName函數,它可以與屬性,方法等一起工作。 – Rauhotz 2009-09-13 11:03:56

+0

這是個好主意:) – Beatles1692 2009-09-13 11:31:04