【问题标题】:Is there something like Python's getattr() in C#?C# 中有类似 Python 的 getattr() 的东西吗?
【发布时间】:2008-09-26 06:35:30
【问题描述】:

C# 中有类似Python's getattr() 的东西吗?我想通过读取包含要放在窗口上的控件名称的列表来创建一个窗口。

【问题讨论】:

    标签: c# python user-interface


    【解决方案1】:

    还有Type.InvokeMember

    public static class ReflectionExt
    {
        public static object GetAttr(this object obj, string name)
        {
            Type type = obj.GetType();
            BindingFlags flags = BindingFlags.Instance | 
                                     BindingFlags.Public | 
                                     BindingFlags.GetProperty;
    
            return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);
        }
    }
    

    可以这样使用:

    object value = ReflectionExt.GetAttr(obj, "PropertyName");
    

    或(作为扩展方法):

    object value = obj.GetAttr("PropertyName");
    

    【讨论】:

      【解决方案2】:

      为此使用反射。

      Type.GetProperty()Type.GetProperties() 分别返回 PropertyInfo 实例,可用于读取对象的属性值。

      var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)
      

      Type.GetMethod()Type.GetMethods() 各自返回MethodInfo 实例,可用于对对象执行方法。

      var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);
      

      如果您不一定知道类型(如果您新属性名称会有点奇怪),那么您也可以这样做。

      var result = dt.GetType().GetProperty("Year").Invoke(dt, null);
      

      【讨论】:

        【解决方案3】:

        是的,你可以这样做...

        typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null);
        

        【讨论】:

          【解决方案4】:

          可以使用 object.GetType().GetProperties() 创建 System.Reflection.PropertyInfo 类。这可用于使用字符串探测对象的属性。 (对象方法、字段等也存在类似的方法)

          但我认为这不会帮助您实现目标。您可能应该直接创建和操作对象。例如,控件具有您可以设置的 Name 属性。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2010-11-18
            • 1970-01-01
            • 2023-03-30
            • 2010-10-31
            • 2011-01-31
            • 1970-01-01
            • 2020-04-10
            相关资源
            最近更新 更多