简体   繁体   中英

C# changing the value of a field of a class for all other classes

I have a class (class A) which has a method named methodA.

class A
{
    public Dictionary<string, double> methodA(double param1, double param2)
    {
      //do calculations
      return result;
    }

}

I have 9 other classes (Class B, C, ....). They all have a field named myField. The value of myField is calculated using methodA of Class A. They look like this:

class B
{
    private Dictionary<string, double> myField;
    private readonly A a = new A();
    public B()
    {
        myField = a.methodA(param1, param2)
    }
    // methods using myField    
}

param1 and param2 are values that never change and are stored elsewhere. So the value of myField is the same for all classes and over the complete runtime of the application. Now there is a design change. methodA is updated and checks if a certain condition is true and calculates the value of myField based on the condition and parameters param3, param4 which are changing during the runtime.

public Dictionary<string, double> methodA(double param1, double param2, double param3, double param4)
{
    if(condition)
    {
        result = .....
    } else {
        result = .....
    }      
    return result;
}

the condition is initially false and changes only once during the runtime. After that the value of myField should stay the same till the end of runtime.

How should I implement this in my class definitions, so that the value of myField is updated once after the condition is true and remains constant till the end of runtime?

You added dependency-injection as a tag yet you don't use it in your examples. Implement it and make Class A an injectable service (using an interface) that has a lifecycle like a singleton, then you inject it in your other classes and voila, you'll have the same instance everywhere with the same values. Here is how I usually do it:

Container.RegisterType<IAPICacheManager, APICacheManager>(new ContainerControlledLifetimeManager());

Then magically it gets passed to your constructors:

public BinanceService(IAPICacheManager apiCache, string instanceName, List<object> tracking, IDataService dataService, IMapper mappingEngine) : base(instanceName, tracking)
    {
        _mappingEngine = mappingEngine;
        _dataService = dataService;

        if (apiCache != null)
        {
            _apiCache = apiCache;

            _cacheEnabled = true;
.....

Here is an example to get you started: Unity

如果myField的值在所有类中必须相同,则考虑将其设为公共静态字段

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM