简体   繁体   English

如何在同一个类的静态List属性中添加类的对象?

[英]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). 我有一个A类,它有2个普通属性(字符串属性)和1个静态属性(A类型列表)。 While creating a new instance of Class A, in constructor, I want to add that instance in static list property. 在构造函数中创建类A的新实例时,我想在静态列表属性中添加该实例。 I have two questions. 我有两个问题。

1- Is it possible? 1-有可能吗?

2- If its possible then how can I implement. 2-如果可能的话,我该如何实施。

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? 1 - 有可能吗?

Yes. 是。

2 - If its possible then how can I implement. 2 - 如果可能的话,我该如何实施。

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) 请参阅静态构造函数(C#编程指南)

Yes its possible and you can implement it inside factoryMethod 是的,它可以在factoryMethod实现

inside this class, add this method to use for creating a new instance and add it to the list -set constractor to private 在此类中,添加此方法以用于创建新实例并将其添加到list -set约束器中以将其添加到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. 对于除List之外的其他类型将正常工作。 For List you have to do the following: 对于List,您必须执行以下操作:

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. 在构造函数中应该将正在构造的对象实例添加到列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM