【问题标题】:Getting Contents of PropertyGrid?获取 PropertyGrid 的内容?
【发布时间】:2009-07-23 02:37:02
【问题描述】:

我是 C# 新手,长期从事 C++ 程序员,我只是想知道曾经使用 .selectedObjects 初始化属性网格。有没有办法获取propertygrid中当前值的内容。

【问题讨论】:

  • 你能澄清你的问题吗?如果您正在设置 SelectedObject,那么您可以访问 PropertyGrid 正在修改的对象,不是吗?

标签: c# propertygrid


【解决方案1】:

PropertyGrid 不会将其内部结构暴露给消费者。

但是,.Net 允许您执行“Refelction”来检查代码的结构(并执行部分代码),包括类属性。

Here 是一篇介绍反射基础知识的文章。实际上,您可以通过反射看到比属性网格显示的更多的内部结构。

【讨论】:

    【解决方案2】:

    您必须使用基于对象类型的反射来遍历网格中对象的所有属性。

    object o = PropertyGrid.SelectedObject;
    Type t = o.GetType();  // We will work on type "t"
    List<MemberInfo> members = new List<MemberInfo>();
    members.AddRange(t.GetProperties(BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);  // Get the public instance properties list
    foreach (MemberInfo member in members)
    {
        Type type = null;
        object value = null;
        PropertyInfo pi = (member as PropertyInfo);
        type = pi.PropertyType;
        if (type.IsSubclassOf(typeof(CollectionBase)))
            continue;  // Sorry
        if (pi.GetCustomAttributes(typeof(NotSerializedAttribute), true).GetLength(0) > 0)
            continue;
        if (!pi.CanRead || !pi.CanWrite)
            continue;
        value = pi.GetValue(o, null);
        // TODO Print out, or save the "value"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 2014-11-12
      • 2014-01-19
      • 2017-03-02
      • 2013-06-27
      • 1970-01-01
      • 2014-10-20
      相关资源
      最近更新 更多