C# how can I preserve data between class instances?

前端 未结 2 1005
余生分开走
余生分开走 2021-01-17 02:31

Apologies for the vague title, but I am not really sure how else to explain it.

Given Class A, B and C.

If Class A contains a List, how can I preserve the da

2条回答
  •  生来不讨喜
    2021-01-17 03:02

    You have multiple options to implement this. As said in other answer you can use Static property/field in Class A for accessing list.

    Second option is to use Dependency injection. Create constructors of class B and class C so that they must be initialized by passing in instance of A. e.g.

    class A
    {
      public List AList {get;set;}
    }
    
    class B
    {
      private A localInstance;
      public B(A instance)
      {
        localInstance = instance;
      }
    
      public void SomeMethod()
      {
         // access to list from instance of A
         var a = localInstance.AList
      }
    }
    
    // Similar implementation for class c
    
        

    提交回复
    热议问题