使在C#中的列表只读 [英] Make a list readonly in c#

查看:329
本文介绍了使在C#中的列表只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的示例代码。我想要做的就是让它使订购数量值只能被写入使用AddNum的方法。

 命名空间的ConsoleApplication1 
{
公共类Person
{
串MYNAME =N / A;
INT myAge = 0;
名单,LT; INT> _nums =新的List< INT>();

公开名单< INT>订购数量
{
得到
{
返回_nums;
}
}

公共无效AddNum(INT NumToAdd)
{

_nums.Add(NumToAdd);
}

公共字符串名称{;组; }
公众诠释年龄{搞定;组; }
}
}



不知怎的,我已经尝试了一堆东西关于AsReadOnly()和只读的关键字,但我似乎无法得到它做我想做的事情。



下面是我的代码样本。要访问属性

 人员P1 =新的Person(); 
p1.Nums.Add(25); //获得1
p1.AddNum(37); //获得2

Console.WriteLine(按任意键);
到Console.ReadLine();



我真的希望获得1失败,而获得2要在 ONLY 的方式,该值可以设置。在此先感谢您的帮助。


解决方案

√务必使用ReadOnlyCollection还,ReadOnlyCollection还的一个子类,
或在IEnumerable的房产罕见的情况下或返回值
和只读的集合。




从报价< A HREF =https://msdn.microsoft.com/en-us/library/dn169389(v=vs.110).aspx相对=nofollow>这篇文章。



您应该有这样的事情:

 列表< INT> _nums =新的List< INT>(); 

公共ReadOnlyCollection还< INT>订购数量
{
得到
{
返回_nums.AsReadOnly();
}
}


I have this example code. What I want to do is to make it so that the "Nums" value can only be written to using the "AddNum" method.

namespace ConsoleApplication1
{
    public class Person
    {
        string myName = "N/A";
        int myAge = 0;
        List<int> _nums = new List<int>();

        public List<int> Nums
        {
            get
            {
                return _nums;
            }
        }

        public void AddNum(int NumToAdd)
        {

            _nums.Add(NumToAdd);
        }

        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Somehow, I've tried a bunch of things regarding AsReadOnly() and the readonly keyword, but I can't seem to get it to do what I want it to do.

Here is the sample of the code I have to access the property.

Person p1 = new Person();
p1.Nums.Add(25); //access 1
p1.AddNum(37); //access 2

Console.WriteLine("press any key");
Console.ReadLine();

I really want "access 1" to fail, and "access 2" to be the ONLY way that the value can be set. Thanks in advance for the help.

解决方案

√ DO use ReadOnlyCollection, a subclass of ReadOnlyCollection, or in rare cases IEnumerable for properties or return values representing read-only collections.

The quote from this article.

You should have something like this:

List<int> _nums = new List<int>();

public ReadOnlyCollection<int> Nums
{
    get
    {
        return _nums.AsReadOnly();
    }
}

这篇关于使在C#中的列表只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆