[英]how to create a static list of objects within their constructor in c#?
我要维护创建的类的所有实例的列表。 我以为可以通过从构造函数中向静态列表添加“ this”来做到这一点。 当然,C#不允许我在构造函数中引用“ this”,因为它尚未完全构造。 这是有道理的,但我正在尝试找出实现此目的的最佳方法。
class Thing
{ static List<Thing> AllTheThings;
public Thing()
{
AllTheThings.Add(this); // can't reference 'this' here
}
}
我可以想到两种方法:
我似乎记得大约20年前在C ++中做过这样的事情,但是不记得细节,也找不到代码。
有人有更好的主意吗?
正如@Jon Skeet所说,提到“ this”应该很好。 但以防万一,这是另一种方法。
public class Thing
{
public readonly static List<Thing> AllTheThings = new List<Thing>();
//making the constructor private so that no other code can call it.
private Thing() { }
//providing a static instance method for creating the object
public static Thing Instance()
{
var t = new Thing();
Thing.AllTheThings.Add(t);
return t;
}
}
现在,在此实现中要注意的事情(打扰双关语)是,通过让应用程序实例化所有“事物”的静态列表,如果您没有办法,则将面临内存泄漏的风险。当范围内不再需要旧的“事物”时,将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.