简体   繁体   English

C#使用静态类创建类的集合或使用集合类

[英]C# to use static class to create collection of the class or to use collection class

I have a design problem, 我有一个设计问题

Basically, I have a class called Currency 基本上,我有一堂课叫做Currency

public class Currency
{ 
     public int ID;
     public string Name;
     public int RoundingValue;

     public Currency() { }

     public void GetData() { // Some SQL query code // }
}

Sometimes it is necessary to fetch all the currencies that there are in the system to make a decision concering exchange rates, compatability of payment, etc. 有时,有必要获取系统中存在的所有货币,以便做出决定汇率,付款兼容性等的决定。

I see two ways of doing that (fetching data): 我看到了两种方法(获取数据):

1) To make a static method inside Currency class to do it. 1)在Currency类中创建一个静态方法来执行此操作。 That involves creating SQL connection instance inside it(not sure if that is the right thing to do), creating List<Currency> instance to store the collection, and then pass it outside the class. 这涉及在其中创建SQL连接实例(不确定是否正确),创建List<Currency>实例以存储集合,然后将其传递给类。

2) Create collection of the class via extending Collections.BaseCollection class, make instance of it, doing the same SQL query, and then return the result. 2)通过扩展Collections.BaseCollection类,创建该类的Collections.BaseCollection ,使其成为实例,并执行相同的SQL查询,然后返回结果。 But that class will provide no additional functionality, and probably won't ever (the same for Currency itself. 但是该类将不提供任何附加功能,而且可能永远不会提供(与Currency本身相同)。

In other cases, I used extended collections, because they needed to store additional info, based on the contents of the collection. 在其他情况下,我使用扩展的集合,因为它们需要根据集合的内容存储其他信息。

But in this case, no additional info is created or functionality provided. 但是在这种情况下,不会创建其他信息或提供任何功能。

So, what design would be more practical? 那么,哪种设计更实用呢? If there is an alternative to the these solutions, I would be more than happy to hear it. 如果有这些解决方案的替代方案,我将非常高兴听到。

I would suggest simply populating a List<Currency> then returning it as IList<Currency> . 我建议简单地填充List<Currency>然后将其返回为IList<Currency> That way if you change it in future to use a custom collection, you won't break any consumers. 这样,如果您将来更改它以使用自定义集合,就不会破坏任何消费者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM