主方法仅在它为空时编译

dii*_*___ -5 c# console-application

我创建了以下程序:

namespace MyNamespace
{
    public enum MyEnum { Jan = 1, Feb = 2, Mar = 3, Apr = 4, May = 5, Jun = 6, Jul = 7, Aug = 8, Sep = 9, Okt = 10, Nov = 11, Dec = 12 }

    class Program
    {
        static void Main(string[] args)
        {
            private static string sourcePath = @"T:\his\is\my\source";
            private static string destinationPath = @"T:\his\is\my\destination";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这就是我所拥有的一切.问题是它不会像这样编译.我得到以下异常:

预期的

它仅在我将Main方法体留空时才有效.当我使用Ctrl+ KD来格式化代码时,它的格式如下:

namespace MyNamespace
{
    public enum MyEnum { SomeField = 1, SomeOtherField = 2, ... }

    class Program
    {
        static void Main(string[] args)
        {
            private static string sourcePath = @"T:\his\is\my\source";
        private static string destinationPath = @"T:\his\is\my\destination";
    }
}
}
Run Code Online (Sandbox Code Playgroud)

这完全没有任何意义.我甚至无法访问参数args:

当前上下文中不存在名称"args"

我真的不知道为什么我的项目表现得像这样.有没有其他人遇到同样的问题?我该怎么办?

Dmi*_*try 10

您不能在方法中声明类字段.
将以下行移出:

private static string sourcePath = @"T:\his\is\my\source";
private static string destinationPath = @"T:\his\is\my\destination";
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望这些变量对于方法是本地的,请将它们声明为:

string sourcePath = @"T:\his\is\my\source";
string destinationPath = @"T:\his\is\my\destination";
Run Code Online (Sandbox Code Playgroud)

  • @Bauss:这些字符串不是必须的 (3认同)
  • `@"T:\ h ..."``添加`@`,拜托 (2认同)
  • 为什么要改为const,解决问题?那是什么逻辑? (2认同)