确保静态类中的数据不会被清理
有没有办法让静态类具有静态数据,并且在函数调用结束时不会清除自身? 即给出:
static class Class1
{
static int[] _array;
static Class1()
{
_array = new[] {2};
}
public static void FillArray()
{
List<int> temp = new List<int>();
for(int i=0;i<100;i++)
temp.Add(i);
_array = temp.ToArray();
}
public static int[] GetArray()
{
return _array;
}
}
如何让 GetArray() 返回除 null 之外的其他内容?
编辑:我想调用这段代码:
int[] array1 = Class1.GetArray();
for (int i = 0; i < array1.Length;i++ )
Console.WriteLine(array1[i]);
Class1.FillArray();
for (int i = 0; i < array1.Length; i++)
Console.WriteLine(array1[i]);
而不是得到两个2。我怎样才能做到这一点?
Is there a way to have a static class have static data that does not clear itself at the end of the function call?
i.e. given:
static class Class1
{
static int[] _array;
static Class1()
{
_array = new[] {2};
}
public static void FillArray()
{
List<int> temp = new List<int>();
for(int i=0;i<100;i++)
temp.Add(i);
_array = temp.ToArray();
}
public static int[] GetArray()
{
return _array;
}
}
How can I get GetArray() to return something other than null?
EDIT: I want to call this code:
int[] array1 = Class1.GetArray();
for (int i = 0; i < array1.Length;i++ )
Console.WriteLine(array1[i]);
Class1.FillArray();
for (int i = 0; i < array1.Length; i++)
Console.WriteLine(array1[i]);
and not get two 2s. How can I make that happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在此代码中,您将获取第一个 int[] {2} 数组的内存地址并将其存储为 array1。然后,当您调用 FillArray() 时,您将创建新的数组列表,并且仅将其内存设置回类中的 _array,而不是 array1。这不是对类中内存的引用,而是对实际原始数组的引用。因此,当您循环返回时,您仍然在查看相同的内存块。
您可能应该这样做:
更新
如果您将 Class1 更改为如下所示,您将看到您正在更改类中的数据。
因为它会在每次调用后打印出数组中的元素。
In this code, you are getting the memory address of the first int[] {2} array and storing that as array1. Then when you call FillArray() you are creating the new List of arrays, and only setting its memory back to the _array in the class, not array1. That is not a reference to the memory in the class, but to the actual original array. So then, when you loop back through, you are still looking at the same memory block.
You should probably be doing this instead:
Update
if you change your Class1 to look like this, you will see that you are changing the data in the class.
Because it will print out the elements in the array after each call.
使用静态构造函数...
use a static constructor...
你可以写类似的东西
you can write something like