日期:2014-05-19  浏览次数:20735 次

关于readonly的小问题
字段不是readonly的,
但是需要属性中要readonly.

例如:
public   class   D
{
                private   IList <int>   list;
                public   IList <int>   List
                {
                        //问题1:如果要get得到的list不允许调用Add,Remove等方法,如何实现?
                        get
                        {
                                //return   list;
                        }
                        //问题2:如果只需要浅拷贝,就这样实现可以吗?
                        set
                        {
                              list   =   value;
                        }
                }
}

------解决方案--------------------
没办法实现,除非用自定义类或接口而不是IList <int>
------解决方案--------------------
复制一个只读的集合吗?每次都复制一遍,太费资源了吧
------解决方案--------------------
复制一个只读的集合.. 太浪费了
------解决方案--------------------
blue_sky007(蓝蓝的天)
你上面的方法可以,但每次读取都会在内存中添加一个实例,这样数据项多的时候会浪费内存和产生效率问题
------解决方案--------------------
to zrh97870(123):

那关于read-only的特性的需求没有实现啊?

“The getter returns a read-only IList wrapper for the current collection.”
~~~~~
我主要的疑惑也在这里
///////////////////////////////////////////////////////////////////////////

自定义一个类,从List <int> 继承,把所有能改变list的方法和属性都覆盖重写。

如:
public class MyIntList : List <int>
{
public new int this[int index]
{
get
{
return base[index];
}
}

public new void Add(int item)
{
throw new Exception( "Can not use this method! ");
}
}