winforms 如果集合具有null项,则出现CollectionEditor错误

lyfkaqu1  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(95)

如果我的数组属性具有null项,则无法从PropertyGrid打开CollectionEditor。出现文本“component”错误。如何修复该错误?

public partial class Form1 : Form
    {
        public Test[] test { get; set; }

        public Form1()
        {
            InitializeComponent();

            test = new Test[5];
            test[2] = new Test() { Name = "2" };

            propertyGrid1.SelectedObject = this;
        }
    }

    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class Test
    {
        public string Name { get; set; }
    }

也许我应该重写我的自定义CollectionEditor中的一些方法,但我不知道是哪个

irtuqstp

irtuqstp1#

这完全取决于您希望如何解决这个问题,但是如果您只需要排除空值,那么您可以覆盖默认的ArrayEditor类,类似于以下内容;

// define the editor on the property
[Editor(typeof(MyArrayEditor), typeof(UITypeEditor))]
public Test[] test { get; set; }

...

public class MyArrayEditor : ArrayEditor
{
    public MyArrayEditor(Type type) : base(type)
    {
    }

    protected override object[] GetItems(object editValue)
    {
        // filter on the objects you want the array editor to use
        return base.GetItems(editValue).Where(i => i != null).ToArray();
    }
}

相关问题