[英]Reference in functions C#
I know from the title you would say it's a duplicate, but... 我从标题中知道您会说这是重复的,但是...
So, I have created my class and made some objects (of class Masina
) in MainWindow
class constructor: 因此,我创建了自己的类,并在MainWindow
类构造函数中创建了一些对象( Masina
类):
public class MainWindow
{ // example
private Masina[] _masina = new Masina[10];
_masina[0].Load(1, 'x'); // works
SomeFunction(_masina);
}
When I use this class functions in Constructor it works fine, but when I try to use some function and pass this argue like this: 当我在Constructor中使用此类函数时,它可以正常工作,但是当我尝试使用某些函数并传递此争论时,如下所示:
public static void SomeFunction(Masina[] masina)
{
for (int i = 0; i < 10; i++)
try
{
masina[i].Load(i, 'x');
}
catch
{
}
}
then SomeFunction takes this argue as not referenced. 然后SomeFunction将此争论视为未引用。 ref
don't work for me! ref
对我不起作用!
Can anyone help me to solve ? 谁能帮我解决?
Probably you want to initialize the Masina[]
array in the constructor , like this: 可能您想在构造函数中初始化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.