在C#中如何定义一个数组的全局变量!

denbes 2007-01-07 04:13:19
我曾经试过用一个静态数组变量来试图定义一个全局的变量,但是这样做会破坏了类的封装性,所以我定义一个为属性,它类型为数组,但是却怎样也不能得到我所要的结果.
代码如下:
在同个命令空间中我定义了二个类,分别为Array1.cs

public class Array1
{
private static int[] StaticVariables;
public int[] Proarray
{
get
{
return StaticVariables;
}
set
{

/*
* 或者用这用方法
* int[] StaticVariables = new int[value.Length];
value.CopyTo (StaticVariables ,0);
*/
int[] StaticVariables = (int[])value.Clone();

}
}
}

与另外一个类Form2.cs

public class Form2 : Form
{

private void button4_Click(object sender, EventArgs e)
{
int[] Orgions = new int[4] { 9, 8, 7, 6 };
Array1 arr = new Array1();
arr.Proarray = Orgions;
MessageBox.Show(arr.Proarray.Length.ToString );

}

}
当我触发 button4_Click事件后,
当我运行到 MessageBox.Show(arr.Proarray.Length.ToString ); 这句时,提示
arr.Proarray 为空?为什么?
...全文
2576 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
liujia_0421 2007-01-20
  • 打赏
  • 举报
回复
try...

set
{

StaticVariables = (int[])value.Clone();

}
marvelstack 2007-01-20
  • 打赏
  • 举报
回复
sorry,修正一下,
n为数组大小。

public class Array1
{
private static int[] StaticVariables = new int[n];
public int[] Proarray
{
get
{
return StaticVariables;
}
set
{

/*
* 或者用这用方法
* int[] StaticVariables = new int[value.Length];
value.CopyTo (StaticVariables ,0);
*/
int[] StaticVariables = (int[])value.Clone();

}
}
}
marvelstack 2007-01-20
  • 打赏
  • 举报
回复

private static int[] StaticVariables;
修改
private static int[] StaticVariables = new [n];
Fibona 2007-01-19
  • 打赏
  • 举报
回复
public static class1
{
public static int[] Orgions = new int[4] { 9, 8, 7, 6 };
}
上海程序员3 2007-01-19
  • 打赏
  • 举报
回复
public static int[] Orgions = new int[4] { 9, 8, 7, 6 };

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧