如何从对象参数获取属性名称?

时间:2009-09-13 10:17:52

标签: c# class

我写了一些实用课程,但如何获得名字?是否可以将参数Name发送给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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

完成Rauhotz答案: Expression.Body可能是一个UnaryExpression(例如对于布尔属性) 以下是使用这些表达式应该做的事情:

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