开发者

Mutable variable available to all classes?

开发者 https://www.devze.com 2023-03-07 10:06 出处:网络
I\'m developing a program in C# and need a mutable variable that is available to all classes in my program.

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. T开发者_JS百科he true value then needs to be conveyed when other classes read it.

How can this be achieved?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消