我已经实现了以下类:
public class ClassAllocator<T>
where T : new()
{
public delegate T Allocator();
T obj;
Allocator allocator = () => new T();
public ClassAllocator( T obj )
{
this.obj = obj;
}
public ClassAllocator( T obj, Allocator allocator )
{
this.obj = obj;
this.allocator = allocator;
}
public T Instance
{
get
{
if( obj == null )
{
obj = allocator();
}
return obj;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我觉得这个简单而有用的东西应该在.NET的某个地方.而且,我意识到我所做的课程有点不正确.该类设计用于处理没有默认构造函数的对象,但我的'where'子句在所有情况下都需要它.
让我知道如果.NET中有什么东西我可以使用,所以我可以摆脱这个类,因为我不想继续使用重新发明的轮.
谢谢!!!!
我正在使用.NET 3.5.对不起,我之前没有提到过这个问题,直到几个好的答案开始流入,我才意识到它是相关的:)