我是C#的新手 - 这几乎是我的第一个程序.我正在尝试创建一些公共静态变量和常量,以便在程序中的任何位置使用.我试过的错误方法是将它们声明在同一命名空间中的一个单独的类中,但它们不在主程序的上下文中.这是一个WPF应用程序.代码如下所示:
namespace testXyz
{
class PublicVars
{
public const int BuffOneLength = 10000;
public static int[] Buff1 = new int[BuffOneLength];
public const int BuffTwoLength = 2500;
public static int[] Buff2 = new int[BuffTwoLength];
private void fillBuff1()
{
Buff1[0] = 8;
Buff1[1] = 3;
//etc
}
private void fillBuff2()
{
Buff2[0] = 5;
Buff2[1] = 7;
//etc
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二档:
namespace testXyz
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static int isInContext = 0;
int jjj = 0, mmm = 0;
private void doSomething()
{
isInContext = 5; // this compiles
if (jjj < BuffOneLength) // "the name 'BuffOneLength' does not exist in the current context"
{
mmm = Buff2[0]; // "the name 'Buff2' does not exist in the current context"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的实际计划当然要长得多.我完全按照所示创建了上面的WPF应用程序来测试这个问题,我也遇到了这些错误,也发生在真正的程序中.我真的不想填充主程序中的数组,因为它们很长并且意味着滚动很多.我还希望有一个地方可以声明某些公共静态变量.这样做的正确方法是什么?
你必须指定类:
// BuffOneLength from PublicVars class
if (jjj < PublicVars.BuffOneLength) {
...
// Buff2 from PublicVars class
mmm = PublicVars.Buff2[0];
Run Code Online (Sandbox Code Playgroud)
或者使用静态:
// When class is not specified, try PublicVars class
using static testXyz.PublicVars;
namespace testXyz {
public partial class MainWindow : Window {
...
// BuffOneLength - class is not specified, PublicVars will be tried
if (jjj < BuffOneLength) {
mmm = Buff2[0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |