离开构造函数后重置数据

Data reset after leaving a constructor

我可能有一个非常初学者的问题,但我不明白为什么会这样。我试图在构造函数中传递一个 StringBuilder,它是通过调试器确定的,但是只要我在调试器中的最后一步离开这个位于不同 class 中的构造函数,它就会返回 null。我知道它是一个引用类型,因此只有一个引用被复制,但即使我通过 "ref" 引用传递它,结果也是一样的......也许我弄错了或者还有其他错误......

class DifferentClass
{
    public void Method()
    {
        StringBuilder[] PathtoFiles = new StringBuilder[numberOfImages];

        for (int i = 0; i < numberOfImages; i++)
        {
            PathtoFiles[i] = new StringBuilder();
            // string pattern for correct file naming/saving
            string nameOfFile = string.Format("{0}{1}{2}", adresaPath, i, ".jpg");
            PathtoFiles[i].Append(nameOfFile);
        }

        Pictures picture = new Pictures(ref PathtoFiles);
    }
}

class Pictures
{
    public StringBuilder[] sb;

    public Pictures(ref StringBuilder[] sb)
    {
        this.sb = sb;
    }

    public Pictures()
    {
    }

    public void LoadPictures(ImageList img)
    {
        for (int i = 0; i < sb.Count(); i++)
        {
            img.Images.Add(string.Format("pic{0}", i), Image.FromFile(sb[i].ToString()));
        }
    }
}

根据要求,这次我在 class 中附上了另一段代码,其中调用了 LoadPictures 方法:

  class ThirdClass
  {   
    DifferentClass diff = new DifferentClass();
    Pictures picture = new Pictures();

    private void btn_Download_Click(object sender, EventArgs e)
    {
        diff.Method();
        //this is a control data is supposed to be saved in
        picture.LoadPictures(imageList1);
    }
  }
public void Method()
{
    // the StringBuilder
    // ...
    Pictures picture = new Pictures(ref PathtoFiles);
}

picture 的初始化是正确的。但它是一个局部变量,当Method()完成后,你就不能再访问它了

您可以修改您的方法以将结果保存在客户端的变量中:

public Pictures Method()
{
    // the StringBuilder
    // ...
    return new Pictures(ref PathtoFiles);
}

客户端

var pics = new DifferentClass().Method();
ImageList imgs = new ImageList();
pics.LoadPictures(imgs);

好了,你去吧:

class ThirdClass
  {   
    DifferentClass diff = new DifferentClass();
    Pictures picture = new Pictures();

    private void btn_Download_Click(object sender, EventArgs e)
    {
        diff.Method();
        //this is a control data is supposed to be saved in
        picture.LoadPictures(imageList1);
    }
  }

您正在使用默认构造函数。哪个不设置 StringBuilder[] Pictures.sb

这当然假设您重新编辑的代码是您正在使用的代码。

在那种情况下,您需要弄清楚如何实例化 DifferentClass,也许在 ThirdClass ctor 中。也许你想要 DifferentClass.Method() 到 return 一个 Picture 对象,你也可以在 ThirdClass 构造函数中初始化它。

有多种方法可以做到这一点。由您选择最佳方法。