什么是只读静态 [英] What is readonly static

查看:75
本文介绍了什么是只读静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请让我知道为什么我可以在下面的代码中更新readonly字典。如果我可以一次又一次地更新它,那就是readonly的用途。



Please let me know why i can update readonly dictionary in below code. If i can update it again and again then whats the purpose of readonly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Myclass m = new Myclass();
            m.Add(1, 5);
            m.Add(6, 10);
            m.Update(6, 545);
        }
    }

    public class Myclass
    {
        private static readonly Dictionary<int, string> Dic = new Dictionary<int, string>();

        public void Add(int x, int y)
        {
            for(int i = x; i<=y; i++)
            {
                Dic.Add(i, "number" + i);
            }
        }

        public void Update(int i, int j)
        {
            Dic[i] = j.ToString(); 
        }


    }
}

推荐答案

Readonly不会阻止您修改集合中的项目,它会阻止您删除或替换集合本身。



有关定义,请参阅readonly(C#参考) [ ^ ]
Readonly does not prevent you from modifying the items in the collection, it prevents you from removing or replacing the collection itself.

For definition, please refer to readonly (C# Reference)[^]


readonly 属性不包含; t影响字典,它影响引用字典的变量。这意味着您可以在字典中添加和删除项目(这很好,因为否则会很难使用)但是您无法创建新字典并将其分配给 Dic 变量,替换现有的变量。

如果在值类型上使用readonly(例如 struct )那么你根本不能改变它(除了在包含类的构造函数中)但是使用引用类型你不能改变对堆上对象的引用,但是你可以自己改变堆值。



如果您愿意,它就像一把车钥匙 - 您无法更换钥匙并仍然进入车内,但一旦您在那里,您可以打开车窗,打开收音机,或开车到商店。只读键不会影响匹配的车辆。
The readonly property doesn;t affect the dictionary, it affects the variable that references the dictionary. What that means is that you can add and remove items from the dictionary (which is good, because otherwise it would be difficult to use) but that you can't create a new dictionary and assign it to the Dic variable, replacing the existing one.
If you use readonly on a value type (a struct for example) then you can't alter it at all (except in the constructor for the containing class) but with a reference type you can't change the reference to the object on the heap, but you can change the heap values themselves.

If you like, it's like a car key - you can't change the key and still get into the car, but once you are in there you can open the windows, turn on the radio, or drive to the shops. A read only key doesn't affect the vehicle it is matched to.


这篇关于什么是只读静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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