如何使IEnumerable的< T>只读?IEnumerable、LT、GT

2023-09-03 11:13:52 作者:失梦

为什么list1Instance和p列出了以下code指向同一个集合的主要方法是什么?

Why is list1Instance and p lists in the Main method of the below code pointing to the same collection?

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的返回类型()这种行为?

Can we change this behavior with out changing the return type of List1.Get()?

感谢

推荐答案

其实,的IEnumerable&LT; T&GT; 已经是只读。这意味着你不能改变底层集合中的任何项目。你不能改变引用到类型集合中被认为。返回类型是不是只读的,但是,因为它是一个引用类型(即),你可以改变通过其参考的原始值。您应该使用结构返回类型(这使得它返回的每个时间值的副本,所以原来的值不会改变,这可能是昂贵的,的方式),或使用只读的人物属性键入来完成这个任务。

In fact, IEnumerable<T> is already readonly. It means you cannot alter any items in the underlying collection. You cannot alter the references to the Person type that are held in the collection. The return type is not read only, however, and since it's a reference type (i.e. a class), you can alter the original values through its reference. You should either use a struct as the return type (that makes a copy of the value each time it's returned, so the original value will not be altered, which can be costly, by the way) or use read only properties on the Person type to accomplish this task.