[英]Does C#.NET have an allocation helper class similar to mine?
I have implemented the following class: 我已经实现了以下类:
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;
}
}
}
I feel like something this simple & useful should be in .NET somewhere. 我觉得这个简单而有用的东西应该在.NET的某个地方。 Also, I realize that the class I made is somewhat incorrect. 而且,我意识到我所做的课程有点不正确。 The class is designed to work with objects that don't have a default constructor, yet my 'where' clause requires it in all cases. 该类设计用于处理没有默认构造函数的对象,但我的'where'子句在所有情况下都需要它。
Let me know if there is something in .NET I can use so I can get rid of this class, as I would hate to continue using a reinvented wheel. 让我知道如果.NET中有什么东西我可以使用,所以我可以摆脱这个类,因为我不想继续使用重新发明的轮。
Thanks!!!! 谢谢!!!!
I'm using .NET 3.5. 我正在使用.NET 3.5。 Sorry I didn't mention this before, I wasn't aware it was relevant until a few good answers started flowing in :) 对不起,我之前没有提到过这个问题,直到几个好的答案开始流入,我才意识到它是相关的:)
Sounds like you're looking for the Lazy<T> Class . 听起来你正在寻找Lazy <T> Class 。
Lazy<T> Class 懒惰的<T>类
Provides support for lazy initialization. 为延迟初始化提供支持。
Lazy initialization occurs the first time the Lazy<T>.Value property is accessed 第一次访问Lazy <T> .Value属性时会发生延迟初始化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.