Mutable variable available to all classes?

偶尔善良 提交于 2019-12-13 04:37:37

问题


I'm developing a program in C# and need a mutable variable that is available to all classes in my program.

For example, I want to set it to a default value, say false, when the program starts, then be able to change it to true later when an action occurs. The true value then needs to be conveyed when other classes read it.

How can this be achieved?


回答1:


How about a static?:

public static class MyProps
{
    public static bool MyProp { get; set; }
}

In your code:

MyProps.MyProp = true;

No initialisation necessary because booleans always initialise to false.




回答2:


Three options:

  • Make it an instance variable of a particular type, and make sure every class has access to the same instance
  • Make it a static variable of a particular type
  • Somewhere in between: make it an instance variable in a singleton type.

Personally I would favour the first approach in conjuction with dependency injection - but think about which classes really need to know about this. Is it really every class in your program?

Global state (via static variables) and singletons make code harder to test in general.

Also, I would definitely make it a private variable and have a property to access it.




回答3:


Sounds like you need a static member in a class somewhere.

class MyClass {
  static bool ms_MyStatic = false;
}

...you can reference this as MyClass.ms_MyStatic wherever you like.



来源:https://stackoverflow.com/questions/6088693/mutable-variable-available-to-all-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!