如何一次声明一个全局数组

时间:2022-09-20 21:29:00

I have a global array but I didn't allocate memory until textbox event change. How can I consider the array created or not?! I wanna run "new arr[6]" one time.

我有一个全局数组,但在textbox事件更改之前我没有分配内存。我怎么能考虑创建或不创建数组?!我想一次运行“新arr [6]”。

Thank you

2 个解决方案

#1


2  

I usually add a readonly property or function for accessing information like this and create the underlying data as needed.

我通常添加一个只读属性或函数来访问这样的信息,并根据需要创建基础数据。

    private static int[] m_Array;

    public static int[] Arr
    {
        get
        {
            if (m_Array == null)
            {
                m_Array = new int[6];
            }
            return m_Array;

        }
    }

#2


0  

You can do lazy creation (allocation, instantiation) with Lazy<> class as well:

您也可以使用Lazy <>类进行延迟创建(分配,实例化):

  // Lazy creation of integer array with 6 items (declaration only, no physical allocation)
  private static Lazy<int[]> m_Array = new Lazy<int[]>(() => new int[6]);

  public static int[] Arr {
    get {
      return m_Array.Value; // <- int[6] will be created here
    }
  }

Whenever you want to check if value (array in this case) is created or not use IsValueCreated:

无论何时想要检查是否创建了值(在这种情况下是数组),都使用IsValueCreated:

  if (m_Array.IsValueCreated) {
    ...

#1


2  

I usually add a readonly property or function for accessing information like this and create the underlying data as needed.

我通常添加一个只读属性或函数来访问这样的信息,并根据需要创建基础数据。

    private static int[] m_Array;

    public static int[] Arr
    {
        get
        {
            if (m_Array == null)
            {
                m_Array = new int[6];
            }
            return m_Array;

        }
    }

#2


0  

You can do lazy creation (allocation, instantiation) with Lazy<> class as well:

您也可以使用Lazy <>类进行延迟创建(分配,实例化):

  // Lazy creation of integer array with 6 items (declaration only, no physical allocation)
  private static Lazy<int[]> m_Array = new Lazy<int[]>(() => new int[6]);

  public static int[] Arr {
    get {
      return m_Array.Value; // <- int[6] will be created here
    }
  }

Whenever you want to check if value (array in this case) is created or not use IsValueCreated:

无论何时想要检查是否创建了值(在这种情况下是数组),都使用IsValueCreated:

  if (m_Array.IsValueCreated) {
    ...