更新只读整数数组? [英] update Readonly int array?

查看:47
本文介绍了更新只读整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在经典意义上,只读对象只能在构造器中设置,以后不能修改.为什么 readonly int 数组的行为有任何不同.

In Classical sense Readonly objects can only be set in the constrcutor and cannot be modified later on. Why do readonly int arrays behave any different.

PS:我知道 Readonly 集合,我只是想知道为什么允许这样做?

PS:I am aware of Readonly collections, I am just curious to know why is this allowed ?

class Class1
{
    public readonly int[] a;

    public Class1()
    {
        a = new int[3];
        a[0] = 1;
        a[1] = 2;
        a[2] = 3;
    }

    public void Update()
    {
        a[0] = 10;
    }
}

推荐答案

Readonly 修饰符应用于它分配给的实际类型.所以在这种情况下,它分配给一个 Array 类型的实例,但不是分配给其中的元素.

Readonly modifier is applied to actual type it assigned to. So in this case it assigned to an Array type instance, but not to a elements present inside it.

这就是为什么,是的,您仍然可以更改元素值,但是代码如

That's why, yes, you still able to change element value, but the code like

public void Update()
{
   a[0] = new int[3];
}

会失败,因为您将更改数组类型实例(而不是其内容)

will fail, as you're going to change Array type instance (and not its content)

希望这会有所帮助.

这篇关于更新只读整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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