要向静态Main()中插入其他方法吗?

时间:2019-05-03 14:31:59

标签: c# visual-studio

首先,我想对这样原始的问题表示歉意,但我是一个完整的初学者,因此找不到能够理解的解决方案。

我正在学习C#(由于Unity),我想尝试一下并自己创建一个小程序。但是,在使用“基本” Visual Studio而不是“统一” Visual Studio进行编码之后,我偶然发现了无法解决或无法理解的问题。

string hello = "Hello, World!";

static void Main()
{
    otherMethod();
}

void otherMethod()
{
    Console.WriteLine(hello);
}

在Unity上,我可以毫无问题地做到这一点,因为Start方法允许在其中使用非静态方法,但是现在...

...如果更改为从Main方法中删除静态,则程序将无法运行。

...如果我将static添加到otherMethod,otherMethod将无法访问字符串hello。

我知道这是原始的,并且在上面的代码中,我可以简单地通过将字符串hello放在otherMethod(等)中来修复它,但这只是一个示例。

如果必须在方法之外使用字符串hello并在Main方法中使用otherMethod,该如何实现?有可能还是我做错了?

2 个答案:

答案 0 :(得分:2)

您不能从静态方法中调用非静态方法。您首先需要实例化该类,然后可以调用这些方法。您的代码的工作示例:

 class Program
{
    string hello = "Hello, World!";
    static void Main(string[] args)
    {
        var test = new Program();
        test.OtherMethod();
    }

    void OtherMethod()
    {
        Console.WriteLine(hello);
    }
}

关于静态与非静态https://hackernoon.com/c-static-vs-instance-classes-and-methods-50fe8987b231

,这是一篇不错的文章

答案 1 :(得分:0)

您是否尝试过将变量设为静态?

        public static string hello = "hello";

这可能不是实现此目标的“正确”方法,但您应该可以对其进行暴力破解。