我的理解是类似直接写代码到老的“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 部分声明变量,那么如何声明它们以便能够从其他类访问它们呢?
我不认为当前接受的答案 https://stackoverflow.com/a/70453334/3025856是正确的,如果您将部分类签名放入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
files
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)