列表上使用的ReadOnly修饰符 [英] ReadOnly modifier used on a list

查看:151
本文介绍了列表上使用的ReadOnly修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

what would happen by using the readonly modifier on the list container.

例如:

what would happen by using the readonly modifier on the list container.

For example:

class Test
{
  private readonly list<string> stringTest = new List<string>();

test()
{}

void changeStringTest()
{
  stringTest.Add("hello");
//Why i am allowed to do this. Readonly should prevent me from doing this by definition where i should only modify the list in the constructor or during initialization 
}

}



还有readonlycollection< string>

有什么区别
在Advance中感谢



Also what is then the difference of readonlycollection<string>


Thanks in Advance

推荐答案

在对引用应用只读"关键字时,可以防止引用更改其指向的对象,但更改该对象是合法的对象本身.
在您的情况下,首次初始化stringTest时,不允许您创建新的List< string>.对象,然后在应用程序中将其分配给stringTest.

When you apply "readonly" keyword to a reference, you prevent the reference from changing the object it is pointing to but it is legal to change the object itself.
In your case, when stringTest is first initialzed, you are not allowed to create a new List<string> object and assign it to stringTest later in your application.

class Test
{
  private readonly list<string> stringTest = new List<string>();

  test(){}
 
  void changeStringTest()
  {
     /* NOT ALLOWED. stringTest is readonly. Its not allowed to change
        the object it is pointing to. */
     stringTest = new List<strnig>();
     
     /* ALLOWED. You are not going to change stringTest but the object.
        Because adding a new item to a list does not affect the
        reference (stringTest) but the object whitch is pointed to by
        stringTest. */
     stringTest.Add("hello");
  }
}
</strnig></string></string>


这篇关于列表上使用的ReadOnly修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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