![](/img/trans.png)
[英]How do I get the Reflection TypeInfo of a C# 9 program that use Top-level statements?
[英]How do I add code outside the scope of Main when using C# 9 Top Level Statements?
我的理解是,將代碼直接寫入舊的“ static void Main(string[] args)
”類似,無需顯示上面的內容。
但是,我曾經在 class 程序中聲明我的變量,以便從其他類訪問它們(如果不是最佳實踐,我很抱歉,我自己學習了 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# 9 的頂級程序功能時,您放棄了在Main
方法 scope 之外放置任何內容的能力。 Main 方法或程序 class 上的字段、屬性、屬性、設置命名空間、更改 class 名稱等都不再可用(唯一的例外是using
行“導入”命名空間)。
如果該限制對您不起作用,請不要使用該功能。
我不認為當前接受的答案是正確的,如果你在Program.cs
中拋出部分 class 簽名,你當然可以添加靜態范圍字段和屬性之類的東西:
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
中的其他代碼將 output:
/home/dongus/bazinga/bin/Debug/net6.0/bazinga
hello world
value
Process finished with exit code 0.
我使用此方法將[ExcludeFromCodeCoverage]
屬性應用於我的項目的Program.cs
文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.