C# how can I preserve data between class instances?

不打扰是莪最后的温柔 提交于 2019-12-04 02:35:26

问题


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 data in that list so that Class B and C can access the data in the list (even if B and C both new up their own instance of Class A)?

Classes B and C must create their own instances (this is out of my control).

I am using this class as my object data source, and let's say I cannot modify the contents of Class C.

Following is an example class:

[DataObject]
public class Product
{
    public string Name {get; set;}
    public string Category {get; set;}
    public int ID {get; set;}

    public List<Product> ProductList =
        new List<Product>();

    [DataObjectMethod(DataObjectMethodType.Select)]
    public IEnumerable<Product> GenerateReport()
    {
        return ProductList;
    }

}

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/44768149/c-sharp-how-can-i-preserve-data-between-class-instances

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