[英]How to create a constructor of a class that return a collection of instances of that class?
My program has the following class definition: 我的程序具有以下类定义:
public sealed class Subscriber
{
private subscription;
public Subscriber(int id)
{
using (DataContext dc = new DataContext())
{
this.subscription = dc._GetSubscription(id).SingleOrDefault();
}
}
}
,where ,哪里
_GetSubscription()
is a sproc which returns a value of type ISingleResult<_GetSubscriptionResult>
_GetSubscription()
是一个存储程序 ,它返回ISingleResult<_GetSubscriptionResult>
类型的值
Say, I have a list of type List<int>
full of 1000 id
s and I want to create a collection of subscribers of type List<Subscriber>
. 说,我有一个List<int>
类型的List<int>
,该列表充满了1000个id
并且我想创建一个List<Subscriber>
类型的订户集合。
How can I do that without calling the constructor in a loop for 1000 times? 如何在不循环调用构造函数1000次的情况下做到这一点?
Since I am trying to avoid switching the DataContext on/off so frequently that may stress the database. 由于我试图避免频繁地打开/关闭DataContext,以免给数据库造成压力。
TIA. TIA。
Write a static factory method which calls a private constructor. 编写一个静态工厂方法来调用私有构造函数。
public sealed class Subscriber
{
// other constructors ...
// this constructor is not visible from outside.
private Subscriber(DataContext dc, int id)
{
// this line should probably be in another method for reusability.
this.subscription = dc._GetSubscription(id).SingleOrDefault();
}
public List<Subscriber> CreateSubscribers(IEnumerable<int> ids)
{
using (DataContext dc = new DataContext())
{
return ids
.Select(x => new Subscriber(dc, x))
// create a list to force execution of above constructor
// while in the using block.
.ToList();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.