【问题标题】:Having issues calling a variable thoughout a program c#在整个程序 c# 中调用变量时遇到问题
【发布时间】:2011-04-26 01:10:03
【问题描述】:

我认为这很简单,但我对如何设置变量“result”感到困惑(请参见下面的代码),因此我可以稍后在程序中调用它,当我希望计时器显示当前的 RAM 使用量时通过安装的总 RAM 来收集使用百分比。 WMI 收集已安装 RAM 的方式让我很失望,因为它必须执行 result["TotalVisibleMemorySize"]。将整个代码块放在计时器中的问题是它每 2 秒刷新一次,因为 WMI 很慢,这确实会延迟计数器。谢谢!

private void Form1_Load(object sender, EventArgs e)
    {
        ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
        ManagementObjectCollection results = searcher.Get();

        foreach (ManagementObject result in results)
        {                
             label1.Text = Convert.ToInt32(result["TotalVisibleMemorySize"]) + " KB";               
        }
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        progressBar1.Value = (int)(performanceCounter1.NextValue() - Convert.ToInt32(result["TotalVisibleMemorySize"]));
        label1.Text = "Processor Time: " + progressBar1.Value.ToString() + "%";                          
    }

【问题讨论】:

    标签: c# variables global-variables call


    【解决方案1】:

    嗯,结果变量在 Form1_Load 方法中。

    您需要将其移到该范围之外,或者作为 Form1 的成员,或者作为全局成员(如在 Program.cs 中)

    我建议不要做一个全局变量,而是创建一个私有变量,例如:

    public class Form1
    {
        private ManagementObjectCollection results;
    ... rest of code
    }
    

    然后,当您需要时,您可以在 Form1 类的其他地方使用 results.Whatever

    【讨论】:

      【解决方案2】:

      你可以在类中声明私有变量:

      private int _totalMemory = 0;
      
      // And in your form load event.
      _totalMemory = Convert.ToInt32(result["TotalVisibleMemorySize"])
      
      // And in your timer tick event.
      progressBar1.Value = (int)(performanceCounter1.NextValue() - _totalMemory);
      

      【讨论】:

        猜你喜欢
        • 2023-03-25
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 1970-01-01
        • 2014-11-10
        • 2013-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多