本文介绍了如何将一个对象从一个方法初始化到另一个类中的另一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在类中,我有2个方法。在method1中,我创建了一个对象,但我不能在method2中使用相同的对象。
为什么?请帮助一个简单的例子。
编码太大,所以我给出了布局
public class Sub
{
}
public class DataLoader
{
public void process1()
{
Sub obj = new Sub();
}
public void process2()
{
//这里我不能使用对象
}
}
解决方案
这样做的原因是。只能从所声明的块中访问 。要从多个方法访问它,请添加字段或将其作为 >
code> class YourClass{
object yourObject;
void Method1()
{
yourObject = new object();
}
void Method2()
{
int x = yourObject.GetHashCode();
}
}
参数: p>
class YourClass
{
void Method1()
{
Method2 ());
}
void Method2(object theObject)
{
int x = theObject.GetHashCode();
}
}
In a class, I have 2 methods. In method1 I created an object, but I can't use the same object in method2.
Why? Please help with a simple example.
The coding is too big, so I have given the layout
public class Sub
{
}
public class DataLoader
{
public void process1()
{
Sub obj = new Sub();
}
public void process2()
{
// here I can't use the object
}
}
解决方案
The reason why this isn't working is scope. A local variable can only be accessed from the block it is declared in. To access it from multiple methods, add a field or pass it to the other method as a parameter.
Field:
class YourClass
{
object yourObject;
void Method1()
{
yourObject = new object();
}
void Method2()
{
int x = yourObject.GetHashCode();
}
}
Parameter:
class YourClass
{
void Method1()
{
Method2(new object());
}
void Method2(object theObject)
{
int x = theObject.GetHashCode();
}
}
这篇关于如何将一个对象从一个方法初始化到另一个类中的另一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!