简体   繁体   中英

How to add the objects of a class in a static List property of same class?

I have a class A and it has 2 normal properties (string properties) and 1 static property (List of type of A). While creating a new instance of Class A, in constructor, I want to add that instance in static list property. I have two questions.

1- Is it possible?

2- If its possible then how can I implement.

I am using following code :

public class A {
private string _property1;
private string _property2;
private static List<A> _AList;

public string Property1 {
  get { return _property1; }
  set { _property1 = value; }
}

public string Property2 {
  get { return _property2; }
  set { _property2 = value; }
}

public static List<A> AList {
  get { return _AList; }
  set { _AList = value; }
}
public A( ) {
}

}

1 - Is it possible?

Yes.

2 - If its possible then how can I implement.

Initialize the list in a static constructor

static A() {
    AList = new List<A>();
}

Then add the instance in the instance constructor

public A( ) {
    A.AList.Add(this);
}

You must create the list either in the declaration or in a static constructor.

private static List<A> _AList = new List<A>();

or

private static List<A> _AList;

static A()
{
    _AList = new List<A>();
}

In the instance constructor you can then add the new item

public A()
{
    A.AList.Add(this);
}

Note: Static constructors cannot be public, since they cannot be called explicitly. They are called automatically before the first instance is created or any static members are referenced.

See Static Constructors (C# Programming Guide)

Yes its possible and you can implement it inside factoryMethod

inside this class, add this method to use for creating a new instance and add it to the list -set constractor to private

public static A CreateInstance ()
{
     A instance = new A();
     if(AList==null)
       AList = new List<A>();
     AList.add(instance);  
     return A;
}

and if you want to create instance from this class anywhere:

A ins = A.CreateInstance ()

For other type except List will work fine. For List you have to do the following:

public static List<A> AList {
 get { 
       if(_AList == null) _AList = new List<A>();
       return _AList; 
     }
 set { _AList = value; }
}

AList.Add(this); in the constructor should add the object instance being constructed to the list.

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