【问题标题】:Reference in functions C#函数 C# 中的引用
【发布时间】:2016-08-18 14:47:39
【问题描述】:

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

所以,我创建了我的类并在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 不要为我工作!

谁能帮我解决?

【问题讨论】:

  • 预期的行为是什么?您看到了什么? “工作”和“不工作”并不是真正有用的问题描述。
  • 参考“不工作”是什么意思,你得到什么错误?这两个代码 sn-ps 是否也在同一个文件中,如果不是曾经引用另一个,或者它们是否在同一个 namspace 中?
  • 这个private Masina[] _masina = new Masina[10]; _masina[0].Load(1, 'x'); 不应该工作,因为数组不包含对实例的引用。
  • 你能提供一个工作的例子吗?当您尝试在任何方法之外调用 _masina[0].Load 时,您的第一个代码 sn-p 甚至都不会编译。而且我确信它不会在构造函数中工作,因为你没有将_masina[0] 设置为任何实例,所以它是null:看看这个:stackoverflow.com/questions/4660142/…

标签: c# wpf reference ref


【解决方案1】:

可能你想在构造函数中初始化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
  }
}

【讨论】:

    猜你喜欢
    • 2010-11-27
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多