C# how can I preserve data between class instances?

前端 未结 2 1003
余生分开走
余生分开走 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:01

    Use static as defined here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static

    Then you will be able to access the class properties instead of instance properties.

    0 讨论(0)
  • 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<object> 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
    
    0 讨论(0)
提交回复
热议问题