c# – 如何使IEnumerable只读?

前端之家收集整理的这篇文章主要介绍了c# – 如何使IEnumerable只读?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么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类型上使用只读属性完成这个任务.
原文链接:https://www.f2er.com/csharp/93612.html

猜你在找的C#相关文章