我是 C# 的新手,长期从事 C++ 程序员,我只是想知道曾经使用 .selectedObjects 初始化属性网格。有没有办法获取propertygrid中当前值的内容。
本
我是 C# 的新手,长期从事 C++ 程序员,我只是想知道曾经使用 .selectedObjects 初始化属性网格。有没有办法获取propertygrid中当前值的内容。
本
PropertyGrid 不会将其内部结构暴露给消费者。
但是,.Net 允许您执行“Refelction”来检查代码的结构(和执行部分),包括类属性。
这是一篇介绍反射基础知识的文章。实际上,您可以通过反射看到比属性网格显示的更多的内部结构。
您必须使用基于对象类型的反射来遍历网格中对象的所有属性。
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"
}