[英]how to create a static list of objects within their constructor in c#?
I want to maintain a list of all instances of my class that are created. 我要维护创建的类的所有实例的列表。 I thought I could do that by adding 'this' to a static list from within the constructor. 我以为可以通过从构造函数中向静态列表添加“ this”来做到这一点。 Of course C# doesn't let me reference 'this' in the constructor because it's not fully constructed yet. 当然,C#不允许我在构造函数中引用“ this”,因为它尚未完全构造。 That makes sense but I'm trying to figure out the best way to accomplish this. 这是有道理的,但我正在尝试找出实现此目的的最佳方法。
class Thing
{ static List<Thing> AllTheThings;
public Thing()
{
AllTheThings.Add(this); // can't reference 'this' here
}
}
I can think of two ways to this: 我可以想到两种方法:
I seem to remember doing something like this in C++ about 20 years ago but don't recall the details and can't find the code. 我似乎记得大约20年前在C ++中做过这样的事情,但是不记得细节,也找不到代码。
Anyone have a better ideas? 有人有更好的主意吗?
As @Jon Skeet said, that reference to "this" should have been fine. 正如@Jon Skeet所说,提到“ this”应该很好。 But just in case, here is an alternate method. 但以防万一,这是另一种方法。
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;
}
}
Now, the thing (excuse the pun) to watch out for in this implementation is that, by having this static list of all "Things" instantiated by the app, you will run the risk of a memory sinkhole if you do not have a way to get rid of old "Things" when they are no longer needed within scope. 现在,在此实现中要注意的事情(打扰双关语)是,通过让应用程序实例化所有“事物”的静态列表,如果您没有办法,则将面临内存泄漏的风险。当范围内不再需要旧的“事物”时,将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.