Array length outside of a method

2019-08-12 05:15发布

问题:

I apologies if this is a duplicate question;

I can find out the number of elements in array:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{

    string[] myThings = new string[] {"Banana", "Dinosaur", "Gwen Stefani"};
    // int l = myThings.Length; // FAIL!

    // Use this for initialization
    void Start ()
    {
        ProcessThings();
    }

    void ProcessThings ()
    {
        //int l = myThings.Length;
        print("Things: " + l);
    }

}

My question is this why can't I declare l= myThings.Length outside of method (line 9)? A field initializer cannot reference the nonstatic field, method, or property `Test.myThings'

Go easy on me, I'm learning :)

Moving up from crayons to C#

回答1:

This is generally not allowed because, the compiler might rearrange the variables and there is no guarantee that the field myThings would be initialized before its length is assigned to l.

As an alternative you can initialize the field l in the constructor.



回答2:

Explanation from C# specs.

10.5.5.2 Instance Field Initialization

A variable initializer for an instance field cannot reference the instance being created. Thus it is a compile-time error to reference this in a variable initializer, because it is a compiletime error for a variable initializer to reference any instance member through a simple-name. In the example

class A
{
    int x = 1;
    int y = x + 1; // Error: reference to instance member of this
}

the variable initializer for y results in a compile-time error because it references a member of the instance being created.



回答3:

"You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before defaultReminder, so the above line might throw a NullReferenceException."

see this link: A field initializer cannot reference the nonstatic field, method, or property

(btw, to do this add static before your type)



回答4:

You are assuming the string array "mythings" is initialized before the integer member variable, by trying to use a property from the string array to initialize the integer.

The order of initialization is not guaranteed. So you cannot do anything which is relying on the order of initialization.