【问题标题】:How to instantiate non-static data items in static main() [duplicate]如何在静态 main() 中实例化非静态数据项 [重复]
【发布时间】:2018-06-27 21:43:15
【问题描述】:

我有一个带有静态 main 方法的 C# 控制台应用程序。

我希望能够在 main 中调用非静态方法,但是 不能。

我认为我需要保持 main 静态,但我也想 在程序中运行非静态方法?

下面的语句说需要一个对象引用。

c1 = new Class1()

我在哪里/如何在这个程序中实例化非静态对象?

谢谢

namespace VER
{
    class Example
    {
        private Dictionary<string, long> dStrLong;
        Class1 c1;

        static void Main(string[] args)
        {
            c1 = new Class1();

        }
    }
}

【问题讨论】:

  • 我认为你把事情搞混了。我会说你先学习一个基本的 c# 教程,然后再回来。
  • c1 = new Class1(); 正在实例化一个对象。使用此访问您的非静态内容。
  • 对象不是静态的,变量是。无论如何,也许你想做Class1 c1 = new Class1();
  • c1 itself 是非静态的,因此您无法从 static 方法访问它。为什么c1 需要成为班级成员?为什么main() 不能在内部声明一个c1 变量?这里的最终目标是什么?
  • 您缺少 OOP 的基础知识。我建议谷歌搜索并了解静态变量和实例变量/方法之间的区别。

标签: c# static main


【解决方案1】:

我认为您需要了解这在幕后是如何工作的。

当您使用静态方法时,系统会为您创建一个静默实例,该实例为静态方法的调用提供服务。

任何不是静态的,都属于您创建的每个实例。这就是编译器说需要对象引用的原因(c1 被声明为实例成员)。

为了让您在main 中使用c1,您可以将其设为静态或将其设为公共成员并创建一个实例以便您可以使用它:

namespace VER
{
    class Example
    {
        private Dictionary<string, long> dStrLong;
        //You can make it static
        static Class1 c1 = new Class1();

        static void Main(string[] args)
        {
            c1.DoSomething();

        }
    }
}

或

namespace VER
{
    class Example
    {
        private Dictionary<string, long> dStrLong;
        //You can make it public
        public Class1 c1 = new Class1();

        static void Main(string[] args)
        {
            var c1 = new Example();
            c1.DoSomething();
        }
    }
}

由于您的代码当前存在,您正试图从静态方法访问属于实例的变量。

无论哪种方式,请确保为变量实例化一个对象。

【讨论】:

  • 非常感谢,正是我要找的东西
【解决方案2】:

如果您将Class1 c1设为静态,您将能够为其分配新对象并调用其非静态方法。

或者,从类中删除 Class1 c1 字段并写入 Class1 c1 = new Class1();。

【讨论】:

    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多