C# 从另一个方法调用在一个方法中实例化的对象的方法
我试图从另一个方法(C# 从另一个方法调用在一个方法中实例化的对象的方法,c#,.net,oop,methods,instantiation,C#,.net,Oop,Methods,Instantiation,我试图从另一个方法(Main())调用在一个方法(objectinstation())中实例化的对象的方法。我可以归结为: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { public
Main()
)调用在一个方法(objectinstation()
)中实例化的对象的方法。我可以归结为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static void ObjectInstantiation()
{
TestClass testClass1 = new TestClass(6);
TestClass testClass2 = new TestClass(7);
}
static void Main()
{
ObjectInstantiation();
testClass1.PrintNumber();
Console.ReadLine();
}
}
class TestClass
{
int number;
public TestClass(int i)
{
number = i;
}
public void PrintNumber()
{
Console.WriteLine(number);
}
}
}
这会引发错误“名称'testClass1'在当前上下文中不存在”
我知道我可以从Main()
中实例化它们,但我还需要从第三个方法中访问对象的方法,与objectinstation()
和Main()
分离,因此我再次遇到同样的问题
我应该补充一点,这个类有多个实例很重要,因为每个实例将存储不同的值
public static void ObjectInstantiation()
{
TestClass testClass1 = new TestClass(6);
TestClass testClass2 = new TestClass(7);
}
这意味着testClass1
和testClass2
是局部变量,它们的范围在objectinstation
中。无法访问其作用域之外的变量
可以在其他方法可以访问的范围内声明变量
static TestClass testClass1;
static TestClass testClass1;
public static void ObjectInstantiation()
{
testClass1 = new TestClass(6);
testClass2 = new TestClass(7);
}
然后在
Main
中使用它们以任何方式引用对象,对该对象的引用必须在范围内。在这种情况下,testClass1
是一个局部变量,它仅在objectinstation
方法的范围内
如果要在Main
方法中引用它,则需要将其设置为类的静态成员:
private static TestClass testClass1;
private static TestClass testClass2;
public static void ObjectInstantiation()
{
testClass1 = new TestClass(6);
testClass2 = new TestClass(7);
}
一旦ObjectInstance()方法返回,testClass1和testClass2就会超出范围。您应该研究变量范围。我已经编辑了您的标题。请参阅“”,其中的共识是“不,他们不应该”。