请问各位大虾有没有可能一个类能否从一个XML文件中动态创建属性。XML的键作为属性名称,值作为属性的值,谢谢了!~~

解决方案 »

  1.   

    (原文在:http://topic.csdn.net/u/20081119/16/dfeb55a4-db4f-444b-a607-d7bd6eb5ff7f.html)要提供动态的属性是要自己写PropertyDescriptor,要很多辅助代码。不过如果是简单的显示和不显示某些属性的特例,则可以利用ExpandableObjectConverter来大大的简化代码。
    下面的例子需要新建一个Winform项目并拉一个PropertyGrid到窗口上,它示范了通过改变ShowDetail属性可以显示和隐藏其他属性:public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }    private void Form1_Load(object sender, EventArgs e)
        {
            this.propertyGrid1.PropertySort = PropertySort.NoSort;
            this.propertyGrid1.SelectedObject = new A();
        }
    }[TypeConverter(typeof(A.PropertyConverter))]                         //<----
    class A
    {
        [RefreshProperties(RefreshProperties.All)]
        public bool ShowDetail { get { return showDetail; } set { showDetail = value; } }
        public string Summary { get { return summary; } set { summary = value; } }
        public string Address1 { get { return address1; } set { address1 = value; } }
        public string Address2 { get { return address2; } set { address2 = value; } }    private class PropertyConverter : ExpandableObjectConverter
        {
            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                PropertyDescriptorCollection collection = TypeDescriptor.GetProperties(value, true);            List<PropertyDescriptor> list = new List<PropertyDescriptor>();
                list.Add(collection["ShowDetail"]);            if ((value as A).ShowDetail)
                {
                    list.Add(collection["Address1"]);
                    list.Add(collection["Address2"]);
                }
                else
                {
                    list.Add(collection["Summary"]);
                }
                
                return new PropertyDescriptorCollection( list.ToArray() );
            }
        }    private bool showDetail;
        private string summary, address1, address2;
    }
      

  2.   

    非要属性么?非要用还真不会。
    不过如果是我, 就会用字典, key和value就行了。为什么一定要用属性呢?
      

  3.   

    如果xml是固定的, 可以反序列化回去。