如何通过非声明其set属性来生成只读C#列表

anm*_*rti 5 .net c# list

List<string> myList我的班级里有一个我想要只为班级用户阅读.

List<strign> myList {get;}

private void SetListValue()
{
    myList = new List<string>();
    myList.Add("ss");
}
Run Code Online (Sandbox Code Playgroud)

像这样我认为我可以myList在我的私有成员中设置我的类中的值,并为类用户提供readonly.但我意识到以这种方式宣布它我无法设置任何价值.

Adr*_*agg 11

尝试:

public List<string> myList {get; private set;}
Run Code Online (Sandbox Code Playgroud)

这可以让你在课堂上设置,但不在外面.请注意,这不会阻止外部客户端更新列表,只会停止对其的引用.

  • 这将阻止消费者替换整个`myList`,但他们仍然可以添加/删除/修改列表内容 (3认同)

STW*_*STW 5

列表,集合等的私有设置器意味着整个列表不能被消费者替换,但它不会保护列表的公共成员.

例如:

public class MyClass
{
  public IList<string> MyList {get; private set;}

  public MyClass()
  {
     MyList = new List<string>(){"One","Two", "Three"};
  }
}

public class Consumer
{
  public void DoSomething()
  {
      MyClass myClass = new MyClass();

      myClass.MyList = new List<string>(); // This would not be allowed,
                                           // due to the private setter

      myClass.MyList.Add("new string"); // This would be allowed, because it's
                                        // calling a method on the existing
                                        // list--not replacing the list itself
    }
}
Run Code Online (Sandbox Code Playgroud)

为了防止消费者改变列表的成员,你可以公开为只读接口,如IEnumerable<string>,ReadOnlyCollection<string>或致电List.AsReadOnly()声明类中.

public class MyClass
{
  public IList<string> MyList {get; private set;}

  public MyClass()
  {
     MyList = new List<string>(){"One","Two", "Three"}.AsReadOnly();
  }
}

public class Consumer
{
  public void DoSomething()
  {
      MyClass myClass = new MyClass();

      myClass.MyList = new List<string>(); // This would not be allowed,
                                           // due to the private setter

      myClass.MyList.Add("new string"); // This would not be allowed, the
                                        // ReadOnlyCollection<string> would throw
                                        // a NotSupportedException
    }
}
Run Code Online (Sandbox Code Playgroud)