tags:

views:

87

answers:

2

i write some utility class but how to get name ? Can that send parameter Name to Mehod not use 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();
            }
        }

Example For use.

    AutoConfig.AutoConfig ac = new AutoConfig.AutoConfig();
    ac.Config.Add(checkBox1.Checked);
    MessageBox.Show(ac.SaveConfig(checkBox1.Checked));
+2  A: 

The only way i know is a hack like this:

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

If you place it in a static class you will get the extension method GetPropertyName.

Then you can use it in your example like

checkbox1.GetPropertyName(cb => cb.Checked)
Rauhotz
can i use ac.Config.Add(checkBox1.Checked); same this but have checkBox1.Name
monkey_boys
+1  A: 

Completing Rauhotz answer : Expression.Body might be a UnaryExpression (for boolean properties for example) Here's what you should do to work with these kind of expressions:

var memberExpression =(expression.Body is UnaryExpression? expression.Body.Operand :expression.Body) as MemberExpression;
Beatles1692
Perhaps we can develop here a general GetMemberName function, that works with properties, methods etc.
Rauhotz
That's a good idea :)
Beatles1692