Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否将其他方法插入到static Main()?_C#_Visual Studio - Fatal编程技术网

C# 是否将其他方法插入到static Main()?

C# 是否将其他方法插入到static Main()?,c#,visual-studio,C#,Visual Studio,首先,我想为这个原始的问题道歉,但我是一个完全的初学者,我无法找到一个我能理解的解决方案 string hello = "Hello, World!"; static void Main() { otherMethod(); } void otherMethod() { Console.WriteLine(hello); } 我学习C是因为Unity,我想做一点实验,自己创建一个小程序。但在用Basic Visual Studio而不是Unity Visual Studio

首先,我想为这个原始的问题道歉,但我是一个完全的初学者,我无法找到一个我能理解的解决方案

string hello = "Hello, World!";

static void Main()
{
    otherMethod();
}

void otherMethod()
{
    Console.WriteLine(hello);
}
我学习C是因为Unity,我想做一点实验,自己创建一个小程序。但在用Basic Visual Studio而不是Unity Visual Studio编写代码之后,我偶然发现了一个无法修复或理解的问题

string hello = "Hello, World!";

static void Main()
{
    otherMethod();
}

void otherMethod()
{
    Console.WriteLine(hello);
}
在Unity上,我可以毫无问题地做到这一点,因为Start方法允许在其中包含非静态方法,但现在

…如果我更改主方法中的remove static,程序将不会运行

…如果我向otherMethod添加static,otherMethod将无法访问字符串hello

我知道这是基本的,在上面的代码中,我可以简单地通过将字符串hello放入otherMethod等来修复它,但这只是一个示例


如果我必须在方法外使用stringhello,在主方法内使用otherMethod,我如何实现它?这是可能的还是我做的完全错误?

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

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

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

这里有一篇关于静态和非静态的文章,你有没有试着让你的变量是静态的

        public static string hello = "hello";

这可能不是实现这一点的“正确”方法,但您应该能够强制执行它。

Main的可能副本应该是静态的,您需要程序的入口点。查看makeothermethodstatic以及hello字段:staticvoidothermethod,staticstringhello=…它不是一个静态方法,因此需要创建该类的实例。只需要var prog=新程序;程序化方法;