首页 > 解决方案 > 控制台应用程序 C# 在运行时声明静态全局 const 变量 args 最佳实践

问题描述

在 C# 控制台应用程序中,我希望能够在运行时设置值,这些值将在程序的整个生命周期中保持不变并且可以全局访问。

应用程序必须能够接受执行参数并被安排执行此操作。例如,在上午 10:00 使用 args name="john" 执行应用程序,在上午 11:00 再次使用 name="jane" 执行。

name 变量一旦运行就不能编辑,并且一旦运行,任何类都应该可以访问它。

我的问题是 - 在运行时设置和存储此变量的最佳方法是什么?

标签: c#oopconsole-application

解决方案


Yes there is. Create your field readonly and initialize it from the constructor like so:

class myClass
{
   public static readonly myField;
   ... // the rest of your fields and get/set methods;
   public myClass(string myField)
   {
      this.MyField = myField; 
   }
}

推荐阅读