使用 C# 9 顶级语句时如何在 Main 范围之外添加代码?

Gui*_*75 13 c# c#-9.0

我的理解是类似于直接把代码写到老的“ static void Main(string[] args)”中,不需要显示上面的内容。

但是,我曾经在类 Program 中声明我的变量,以便从其他类访问它们(抱歉,如果不是最佳实践,我自己学习了 C#,只要它有效,我对我的代码很满意)。请参阅下面的示例:

using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;

namespace myNameSpace
{
    class Program
    {
        //variables declaration
        public static string abc = "abc";
        public static int xyz = 1;

        static void Main(string[] args)
        {
            //code goes here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 C# 9,似乎我只能在 Main 部分声明变量,那么如何声明它们以便能够从其他类访问它们呢?

don*_*gus 20

我不认为当前接受的答案是正确的,如果您添加部分类签名,那么Program.cs您肯定可以添加静态范围的字段和属性之类的内容:

var customAttributes = (CustomAttribute[])typeof(Program).GetCustomAttributes(typeof(CustomAttribute), true);
Console.WriteLine(customAttributes[0].SomePropery);
Console.WriteLine(MyField);


[Custom(SomePropery = "hello world")]
public partial class Program
{ 
    private const string MyField = "value";
}

class CustomAttribute : Attribute
{
    public string SomePropery { get; set; }
}

Run Code Online (Sandbox Code Playgroud)

上面的代码Program.cs不会输出任何其他内容:

/home/dongus/bazinga/bin/Debug/net6.0/bazinga
hello world
value

Process finished with exit code 0.
Run Code Online (Sandbox Code Playgroud)

我使用此方法将该[ExcludeFromCodeCoverage]属性应用于我的项目Program.cs文件


gun*_*171 13

对于.NET 5:

当您使用C# 9 的顶级程序功能时,您就放弃了将任何内容置于方法范围之外的能力Main。Main 方法或 Program 类上的字段、属性、属性、设置命名空间、更改类名称等都不再可用(唯一的例外是用行“导入”命名空间using)。

如果该限制不适合您,请不要使用该功能。


对于 .NET 6 及更高版本,请使用dongus 的答案