如何调用Class = new Class();宣布一次?

时间:2017-08-02 08:37:16

标签: c# winforms class methods

在Windows窗体应用程序中,我接到电话

  private Class1 c1;
  private void Print()
  {
            c1 = new Class1();
  }

但是在下一篇文章中,我不想宣布新的Class,因为它为我的程序设置了错误的值并得到了错误。       它就像

  private void Print2()
  {
            c1 ; //**( I don't want to declare new one )**
  }

编辑2       我喜欢像你说的那样,但我的代码中的参数就像

    public CandleCollection GetCandleCollection()
    {
        CandleCollection collection = null;
        try
        {
            collection = SymbolList[cbxSymbol.Text];
        }
        catch (Exception) { }
        return collection;
    }       
    private Class1 c1 = new Class1(<collection>);  **it's need to call collection**
    private void Print()
    {
            c1 = new Class1();
    }
    private void Print2()
    {
            c1 ; //**( I don't want to declare new one )**
    }

编辑3        这是我调用c1的原始代码

    private void Print()
    {
        CandleCollection collection = GetCandleCollection();
        Class1 c1 = new Class1(collection);
    }

1 个答案:

答案 0 :(得分:1)

CandleCollection变量移出public方法,这样您也可以使用此方法。

然后,您只能实例化Class1变量一次:

private CandleCollection collection = null;

public CandleCollection GetCandleCollection()
{
    try
    {
        collection = SymbolList[cbxSymbol.Text];
    }
    return collection;
}       
private Class1 c1 = new Class1(collection);
private void Print()
{
        c1;
}
private void Print2()
{
        c1;
}