【问题标题】:How do I add code outside the scope of Main when using C# 9 Top Level Statements?使用 C# 9 顶级语句时,如何在 Main 范围之外添加代码?
【发布时间】:2022-01-23 22:04:07
【问题描述】:

我的理解是直接把代码写到旧的“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
        }
    }
}

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

【问题讨论】:

  • 如果您需要在入口点之外声明变量(即字段),顶级语句不适合您。这不是灵丹妙药。

标签: c# c#-9.0


【解决方案1】:

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

如果该限制对您不起作用,请不要使用该功能。

【讨论】:

  • 似乎顶级语句和顶级程序可以互换使用。我找不到这些术语之间有意义的区别,所以如果有,请告诉我。
【解决方案2】:

我认为答案不正确,如果您在 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; }
}

上面的代码和Program.cs中的其他代码都不会输出:

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

Process finished with exit code 0.

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

【讨论】:

    猜你喜欢
    • 2023-01-27
    • 1970-01-01
    • 2011-07-03
    • 2022-11-13
    • 2021-12-25
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    相关资源
    最近更新 更多