防止从外部类C#访问列表元素

rustyBucketBay

可能是这个问题的延续

我进入了一个类列表的需求,在List<Foo>这里我想限制对列表元素的访问,而不是对整个列表的访问,以便我可以获取/设置整个列表,但不能获取/设置其任何元素。

挑战在于,由于列表元素的序列化,列表元素的类型需要是一个公共类,其所有成员(即属性)都是公共的。

有什么办法可以实现呢?

提前致谢

编辑:

我试图这样做:

public class SomeClass()
{
    private List<string> someList;
    public IList<string> SomeList { 
        get { return someList.AsReadOnly(); }
    }
}

并检查是否有可能是我提供任何必要方法将是一种get { return someList.AsWholeListGettable&SettableOnly(); }get { return someList.AsNoAccessibleElementsList(); }

我还尝试了[]运算符重载,以使索引运算符变得私有。(数组的相同行为也是可以接受的)。

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer to allow client code to use [] notation.
    private T this[int i]
    {
        private get { return arr[i]; }
        private set { arr[i] = value; }
    }
}

如在这里

这样,来自外部的班级成员就无法进入。但是我得到这个错误:

在此处输入图片说明

rustyBucketBay

天哪,我正在发布答案,以防对任何人有用。将index属性设置为private可以按照我的要求运行:

    class SampleCollection<T> {
        // Declare an array to store the data elements.
        private T[] arr = new T[100];

        // Define the indexer to allow client code to use [] notation.
        private T this[int i] {
            get { return arr[i]; }
            set { arr[i] = value; }
        }
    }

我的问题是我将属性和访问器双重设置为私有,所以这就是我得到错误的原因。在产生错误的代码下方:

    private T this[int i]
    {
        private get { return arr[i]; }
        private set { arr[i] = value; }
    }

将index属性设置为private,您可以锁定对列表索引的访问,因此无法获取或设置元素,并且可以使用其他方法来处理整个list元素的批量处理。那就是我想要的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章