在课堂上,我有两种方法.在method1中我创建了一个对象,但我不能在method2中使用相同的对象.
为什么?请帮助一个简单的例子.
编码太大了,所以我给出了布局
public class Sub
{
}
public class DataLoader
{
public void process1()
{
Sub obj = new Sub();
}
public void process2()
{
// here I can't use the object
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用的原因是范围.甲局部变量只能从它中声明的块进行访问.要从多个方法访问它,添加一个字段或将它传递给其他的方法作为参数.
领域:
class YourClass
{
object yourObject;
void Method1()
{
yourObject = new object();
}
void Method2()
{
int x = yourObject.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
参数:
class YourClass
{
void Method1()
{
Method2(new object());
}
void Method2(object theObject)
{
int x = theObject.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)