加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使IEnumerable只读?

发布时间:2020-12-15 03:51:40 所属栏目:百科 来源:网络整理
导读:为什么list1Instance和p列表在下面代码的Main方法中指向同一集合? class Person { public string FirstName = string.Empty; public string LastName = string.Empty; public Person(string firstName,string lastName) { this.FirstName = firstName; this
为什么list1Instance和p列表在下面代码的Main方法中指向同一集合?
class Person
    {
        public string FirstName = string.Empty;
        public string LastName = string.Empty;

        public Person(string firstName,string lastName) {
            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

    class List1
    {
        public List<Person> l1 = new List<Person>();

        public List1()
        {
            l1.Add(new Person("f1","l1"));
            l1.Add(new Person("f2","l2"));
            l1.Add(new Person("f3","l3"));
            l1.Add(new Person("f4","l4"));
            l1.Add(new Person("f5","l5"));
        }
        public IEnumerable<Person> Get()
        {
            foreach (Person p in l1)
            {
                yield return p;
            }

            //return l1.AsReadOnly(); 
        }

    }  

    class Program
    {

        static void Main(string[] args)
        {
            List1 list1Instance = new List1();

            List<Person> p = new List<Person>(list1Instance.Get());           

            UpdatePersons(p);

            bool sameFirstName = (list1Instance.l1[0].FirstName == p[0].FirstName);
        }

        private static void UpdatePersons(List<Person> list)
        {
            list[0].FirstName = "uf1";
        }
    }

我们可以通过更改List1.Get()的返回类型来更改此行为吗?

谢谢

解决方法

实际上,IEnumerable< T>已经是只读的这意味着您不能更改底层集合中的任何项目.您不能更改对集合中保留的Person类型的引用.但返回类型不是只读的,因为它是一个引用类型(即一个类),所以可以通过引用来更改原始值.您应该使用一个结构体作为返回类型(每次返回时都会创建一个值,所以原始值不会被更改,这可能是昂贵的)或者在Person类型上使用只读属性完成这个任务.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读