Use*_*892 3 c# static properties
我有一个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( ) {
}
Run Code Online (Sandbox Code Playgroud)
}
1 - 有可能吗?
是.
2 - 如果可能的话,我该如何实施.
在静态构造函数中初始化列表
static A() {
AList = new List<A>();
}
Run Code Online (Sandbox Code Playgroud)
然后在实例构造函数中添加实例
public A( ) {
A.AList.Add(this);
}
Run Code Online (Sandbox Code Playgroud)