问题
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