方法外部的数组长度 [英] Array length outside of a method

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

问题描述

如果这是一个重复的问题,我深表歉意;

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);
    }

}

我的问题是为什么我不能在方法之外声明l = myThings.Length(第9行)? 字段初始化程序无法引用非静态字段,方法或属性"Test.myThings"

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 :)

从蜡笔升级到C#

推荐答案

通常不允许这样做,因为编译器可能会重新排列变量,并且不能保证在将字段myThings的长度分配给l之前将其初始化.

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.

或者,您可以在构造函数中初始化字段l.

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

这篇关于方法外部的数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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