【问题标题】:Restricting edits for collections of value types in general (and in PropertyGrid)限制对一般值类型集合的编辑(以及在 PropertyGrid 中)
【发布时间】:2015-10-26 16:53:50
【问题描述】:

我的班级有一组布尔值。我想允许更改值,但限制添加或删除它们。 (特别是在 PropertyGrid 控件中)。

到目前为止我已经用谷歌搜索了

.AsReadOnly()

方法作为推荐的解决方案,但与引用类型的集合(添加/删除受限,更改的值成功保存)相比,它对值类型的集合(添加/删除受限,但更改的值不保存)的工作方式不同.

我为这种行为做了一个简短的例子: 考虑一个包装布尔值的类:

class boolWrapper
{
    public bool boolValue { get; set; }

    public boolWrapper (bool boolValue)
    {
        this.boolValue = boolValue;
    }
}

以及使用这两种集合的其他类:

class testClassWithArray
{
    // Collection of booleans
    private List<bool> _boolArray;
    public ReadOnlyCollection<bool> boolArray
    {
        get { return _boolArray.AsReadOnly(); }
    }

    // Collection of wrapped booleans
    private List<boolWrapper> _boolWrappedArray;
    public ReadOnlyCollection<boolWrapper> boolWrappedArray
    {
        get { return _boolWrappedArray.AsReadOnly(); }
    }

    // Filling collections with some values
    public testClassWithArray()
    {
        _boolArray = new List<bool>();
        _boolWrappedArray = new List<boolWrapper>();

        for (int i = 0; i < 3; i++)
        {
            _boolArray.Add(false);
            _boolWrappedArray.Add(new boolWrapper(false));
        }
    }
}

让我们分配给一个 PropertyGrid:

        testClassWithArray testArr = new testClassWithArray();
        testPropertyGrid.SelectedObject = testArr;

当更改两个集合(boolWrappedArray、boolArray)的值时,新值会成功地被包装值的集合应用,但不会被另一个集合应用。

虽然这种行为可能是可以理解的,但有没有办法不使用包装类、限制添加/删除操作并为值类型的集合应用新值?

【问题讨论】:

    标签: c# winforms collections properties propertygrid


    【解决方案1】:

    虽然这种行为可能是可以理解的,但有没有办法不使用包装类、限制添加/删除操作并为值类型的集合应用新值?

    虽然一般不推荐,但完成您所要求的最简单的方法是公开诸如 Array 之类的集合(没有添加/删除,只需编辑,不幸的是没有任何控制(验证)),像这样

    class testClassWithArray
    {
        // Collection of booleans
        public bool[] boolArray { get; private set; }
    
        // Collection of wrapped booleans
        private List<boolWrapper> _boolWrappedArray;
        public ReadOnlyCollection<boolWrapper> boolWrappedArray
        {
            get { return _boolWrappedArray.AsReadOnly(); }
        }
    
        // Filling collections with some values
        public testClassWithArray()
        {
            boolArray = new bool[3];
            _boolWrappedArray = new List<boolWrapper>();
            for (int i = 0; i < 3; i++)
            {
                _boolWrappedArray.Add(new boolWrapper(false));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多