简体   繁体   中英

Changing value of readonly array

I have this jagged array in C#:

    private static readonly float[][] Numbers = {
    new float[]{ 0.3f, 0.4f, 0.5}};

How can I override the value?

public static void SetNewNumbers(float[][] num){
    Numbers = num;}

This is not working because of readonly,what should be added? ( I cant change anything about Numbers)

here is the info you need:

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.

when you declare Numbers read only then this is not allowed

Numbers = num

coz you can not change the reference but you can modify the object...

so this is valid:

Numbers[0] = new[] {0.0f, 0.0f, 0.0f};
Numbers[0][1] = 1.0f;

You can reassign each value in Numbers assuming the new array matches:

void ResetNumbers(float[][] num) {
    if (num.Length != Numbers.Length || num[0].Length != Numbers[0].Length)
        throw new ArgumentException($"{nameof(num)} dimensions incorrect");

    for (int j1 = 0; j1 < Numbers.Length; ++j1) {
        for (int j2 = 0; j2 < Numbers[j1].Length; ++j2) {
            Numbers[j1][j2] = num[j1][j2];
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM