【问题标题】:Calling the methods of an object instantiated in one method, from another method从另一种方法调用在一种方法中实例化的对象的方法
【发布时间】:2014-12-10 00:28:24
【问题描述】:

我正在尝试从另一种方法 (Main()) 调用在一种方法 (ObjectInstantiation()) 中实例化的对象的方法。我归结为:

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() 中实例化它们,但我还需要从第三种方法中访问对象的方法,与ObjectInstantiation()Main() 分开,所以我又遇到了同样的问题。

我应该补充一点,类的多个实例很重要,因为每个实例将存储不同的值。

【问题讨论】:

  • 一旦 ObjectInstantiation() 方法返回,testClass1 和 testClass2 就会超出范围。
  • 你应该研究变量范围。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# .net oop methods instantiation


【解决方案1】:

为了以任何方式引用对象,对该对象的引用必须在范围内。在这种情况下,testClass1 是一个局部变量,它只在ObjectInstantiation 方法的范围内。

如果你想在Main方法中引用它,你需要让它成为类的静态成员:

private static TestClass testClass1;
private static TestClass testClass2;


public static void ObjectInstantiation()
{
    testClass1 = new TestClass(6);
    testClass2 = new TestClass(7);
}

【讨论】:

    【解决方案2】:
    public static void ObjectInstantiation()
    {
        TestClass testClass1 = new TestClass(6);
        TestClass testClass2 = new TestClass(7);
    }
    

    这意味着testClass1testClass2 是局部变量,它们的作用域在ObjectInstantiation 内。您无法访问其范围之外的变量。

    你可以在你想要的其他方法可以访问的范围内声明你的变量。

    static TestClass testClass1;
    static TestClass testClass1;
    
    public static void ObjectInstantiation()
    {
        testClass1 = new TestClass(6);
        testClass2 = new TestClass(7);
    }
    

    然后在Main中使用它们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2013-02-10
      • 2020-06-18
      • 2012-03-22
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多