繁体   English   中英

函数C#中的引用

[英]Reference in functions C#

我从标题中知道您会说这是重复的,但是...

因此,我创建了自己的类,并在MainWindow类构造函数中创建了一些对象( Masina类):

public class MainWindow
{ // example
     private Masina[] _masina = new Masina[10];
     _masina[0].Load(1, 'x');   // works
     SomeFunction(_masina);
}

当我在Constructor中使用此类函数时,它可以正常工作,但是当我尝试使用某些函数并传递此争论时,如下所示:

public static void SomeFunction(Masina[] masina) 
    {
        for (int i = 0; i < 10; i++)
            try
            {
                masina[i].Load(i, 'x');
            }
            catch
            {
            }
    }

然后SomeFunction将此争论视为未引用。 ref对我不起作用!

谁能帮我解决?

可能您想在构造函数中初始化Masina[]数组,如下所示:

public class MainWindow {
  // Declaraion is OK, calling method _masina[0].Load(1, 'x') - is not
  private Masina[] _masina = new Masina[10];

  // constructor is the place you're supposed to put complex initialization to
  public MainWindow() {
    // You can call the method in the constructor
    SomeFunction(_masina);
  }

  public static void SomeFunction(Masina[] masina) {
    // validate arguments in the public methods
    if (null == masina)
      throw new ArgumentNullException("masina");

    // do not use magic numbers (10), but actual parameters (masina.Length)
    for (int i = 0; i < masina.Length; ++i)
      masina[i].Load(i, 'x');

    // hiding all exceptions - catch {} - is very bad idea
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM