简体   繁体   English

如何创建一个类的构造函数以返回该类的实例的集合?

[英]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.

相关问题 使用StructureMap创建需要构造函数参数的类的实例 - Create instances of a class that needs a constructor argument with StructureMap 如何创建抽象构造函数或获取抽象类的类型并返回它? - How to create an abstract constructor or get type of abstract class and return it? 类在静态构造函数中创建其自身的实例是否安全? - Is it safe for a class to create instances of itself inside the static constructor? 如何编写返回实例集合的类方法 - How to write class methods that return collections of instances 如何创建基本字符类的实例 - How to create instances of a base character class 如何创建和使用作为 class 实例的项目列表 - How to create and use a list of items that are instances of a class C#如何创建类的特殊实例? - C# How to create special instances of a class? 如何在更好的实践中创建复杂类的实例? - How to create instances of complex class in a better practice? 如何动态创建 class 实例并调用实现 - How to create the class instances dynamically and call the implementation 如何在构造函数执行期间在异常处理程序中分配类实例 - How to assign class instances in exception handler during constructor execution
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM