[英]How to add the objects of a class in a static List property of same class?
我有一个A类,它有2个普通属性(字符串属性)和1个静态属性(A类型列表)。 在构造函数中创建类A的新实例时,我想在静态列表属性中添加该实例。 我有两个问题。
1-有可能吗?
2-如果可能的话,我该如何实施。
我使用以下代码:
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 - 有可能吗?
是。
2 - 如果可能的话,我该如何实施。
在静态构造函数中初始化列表
static A() {
AList = new List<A>();
}
然后在实例构造函数中添加实例
public A( ) {
A.AList.Add(this);
}
您必须在声明或静态构造函数中创建列表。
private static List<A> _AList = new List<A>();
要么
private static List<A> _AList;
static A()
{
_AList = new List<A>();
}
在实例构造函数中,您可以添加新项
public A()
{
A.AList.Add(this);
}
注意:静态构造函数不能是公共的,因为它们不能显式调用。 在创建第一个实例或引用任何静态成员之前会自动调用它们。
是的,它可以在factoryMethod
实现
在此类中,添加此方法以用于创建新实例并将其添加到list -set约束器中以将其添加到private
public static A CreateInstance ()
{
A instance = new A();
if(AList==null)
AList = new List<A>();
AList.add(instance);
return A;
}
如果你想在任何地方从这个类创建实例:
A ins = A.CreateInstance ()
对于除List之外的其他类型将正常工作。 对于List,您必须执行以下操作:
public static List<A> AList {
get {
if(_AList == null) _AList = new List<A>();
return _AList;
}
set { _AList = value; }
}
AList.Add(this);
在构造函数中应该将正在构造的对象实例添加到列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.