C# List<BusinessObject> 还是 BusinessObjectCollection?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-01 09:08:38  来源:igfitidea点击:

List<BusinessObject> or BusinessObjectCollection?

提问by FlySwat

Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable

在 C# 泛型之前,每个人都会通过创建一个实现 IEnumerable 的集合库来为其业务对象编码集合

IE:

IE:

public class CollectionBase : IEnumerable

and then would derive their Business Object collections from that.

然后从中派生出他们的业务对象集合。

public class BusinessObjectCollection : CollectionBase

Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:

现在有了通用列表类,有没有人直接使用它?我发现我使用了两种技术的折衷方案:

public class BusinessObjectCollection : List<BusinessObject>

I do this because I like to have strongly typed names instead of just passing Lists around.

我这样做是因为我喜欢使用强类型名称而不是仅仅传递列表。

What is yourapproach?

你的方法是什么?

采纳答案by Scott Wisniewski

I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time.

我通常是直接使用 List 的阵营,除非出于某种原因我需要封装数据结构并提供其功能的有限子集。这主要是因为如果我没有特定的封装需求,那么这样做只是浪费时间。

However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes.

但是,使用 C# 3.0 中的聚合初始化功能,在一些新情况下我会提倡使用自定义集合类。

Basically, C# 3.0 allows any class that implements IEnumerableand has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax:

基本上,C# 3.0 允许任何实现IEnumerable并具有 Add 方法的类使用新的聚合初始值设定项语法。例如,因为 Dictionary 定义了一个 Add(K key, V value) 方法,所以可以使用以下语法初始化字典:

var d = new Dictionary<string, int>
{
    {"hello", 0},
    {"the answer to life the universe and everything is:", 42}
};

The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection:

该功能的伟大之处在于它适用于具有任意数量参数的添加方法。例如,给定这个集合:

class c1 : IEnumerable
{
    void Add(int x1, int x2, int x3)
    {
        //...
    }

    //...
}

it would be possible to initialize it like so:

可以像这样初始化它:

var x = new c1
{
    {1,2,3},
    {4,5,6}
}

This can be really useful if you need to create static tables of complex objects. For example, if you were just using List<Customer>and you wanted to create a static list of customer objects you would have to create it like so:

如果您需要创建复杂对象的静态表,这可能非常有用。例如,如果您只是使用List<Customer>并且想要创建客户对象的静态列表,则必须像这样创建它:

var x = new List<Customer>
{
    new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"),
    new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"),
    new Customer("Michael Scott", "555-555-8769", "Scranton PA"),
    new Customer("Ali G", "", "Staines", "UK")
}

However, if you use a customized collection, like this one:

但是,如果您使用自定义集合,如下所示:

class CustomerList  : List<Customer>
{
    public void Add(string name, string phoneNumber, string city, string stateOrCountry)
    {
        Add(new Customer(name, phoneNumber, city, stateOrCounter));
    }
}

You could then initialize the collection using this syntax:

然后,您可以使用以下语法初始化集合:

var customers = new CustomerList
{
    {"Scott Wisniewski", "555-555-5555", "Seattle", "WA"},
    {"John Doe", "555-555-1234", "Los Angeles", "CA"},
    {"Michael Scott", "555-555-8769", "Scranton PA"},
    {"Ali G", "", "Staines", "UK"}
}

This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex.

这具有更易于输入和阅读的优点,因为它们无需为每个元素重新输入元素类型名称。如果元素类型很长或很复杂,这种优势会特别明显。

That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database.

话虽如此,这仅在您需要应用程序中定义的静态数据集合时才有用。某些类型的应用程序,如编译器,一直在使用它们。其他的,比如典型的数据库应用程序不会,因为它们从数据库加载所有数据。

My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use List<T>directly.

我的建议是,如果您需要定义对象的静态集合,或者需要封装集合接口,则创建一个自定义集合类。否则我就直接使用List<T>

回答by Matt Hamilton

I generally only derive my own collection classes if I need to "add value". Like, if the collection itself needed to have some "metadata" properties tagging along with it.

如果我需要“增加价值”,我通常只派生我自己的集合类。就像,如果集合本身需要一些“元数据”属性与之一起标记。

回答by Scott Muc

I've been going back and forth on 2 options:

我一直在来回选择 2 个选项:

public class BusinessObjectCollection : List<BusinessObject> {}

or methods that just do the following:

或仅执行以下操作的方法:

public IEnumerable<BusinessObject> GetBusinessObjects();

The benefits of the first approach is that you can change the underlying data store without having to mess with method signatures. Unfortunately if you inherit from a collection type that removes a method from the previous implementation, then you'll have to deal with those situations throughout your code.

第一种方法的好处是您可以更改底层数据存储,而不必弄乱方法签名。不幸的是,如果您从一个从先前实现中删除方法的集合类型继承,那么您将不得不在整个代码中处理这些情况。

回答by jeremcc

I do the exact same thing as you Jonathan... just inherit from List<T>. You get the best of both worlds. But I generally only do it when there is some value to add, like adding a LoadAll()method or whatever.

我做和你完全一样的事情乔纳森......只是继承自List<T>. 您可以两全其美。但我通常只在有一些价值要添加时才这样做,比如添加一个LoadAll()方法或其他什么。

回答by AdamSane

6 of 1, half dozen of another

1 个中的 6 个,另一个半打

Either way its the same thing. I only do it when I have reason to add custom code into the BusinessObjectCollection.

无论哪种方式都是一样的。我只在有理由将自定义代码添加到 BusinessObjectCollection 时才这样做。

With out it having load methods return a list allows me to write more code in a common generic class and have it just work. Such as a Load method.

如果没有加载方法返回一个列表,我可以在一个通用的通用类中编写更多代码并让它正常工作。比如Load方法。

回答by tghw

I prefer just to use List<BusinessObject>. Typedefing it just adds unnecessary boilerplate to the code. List<BusinessObject>is a specific type, it's not just any Listobject, so it's still strongly typed.

我更喜欢只使用List<BusinessObject>. 对它进行类型定义只是在代码中添加了不必要的样板。 List<BusinessObject>是一个特定的类型,它不仅仅是任何List对象,所以它仍然是强类型的。

More importantly, declaring something List<BusinessObject>makes it easier for everyone reading the code to tell what types they are dealing with, they don't have to search through to figure out what a BusinessObjectCollectionis and then remember that it's just a list. By typedefing, you'll have to require a consistent (re)naming convention that everyone has to follow in order for it to make sense.

更重要的是,声明一些东西List<BusinessObject>使每个阅读代码的人都可以更容易地分辨出他们正在处理的类型,他们不必搜索以找出 aBusinessObjectCollection是什么,然后记住它只是一个列表。通过 typedefing,您必须需要一个一致的(重新)命名约定,每个人都必须遵循该约定才能使其有意义。

回答by Outlaw Programmer

You should probably avoid creating your own collection for that purpose. It's pretty common to want to change the type of data structure a few times during refactorings or when adding new features. With your approach, you would wind up with a separate class for BusinessObjectList, BusinessObjectDictionary, BusinessObjectTree, etc.

您可能应该避免为此目的创建自己的集合。在重构或添加新功能时,想要多次更改数据结构的类型是很常见的。使用您的方法,您最终会为 BusinessObjectList、BusinessObjectDictionary、BusinessObjectTree 等创建一个单独的类。

I don't really see any value in creating this class just because the classname is more readable. Yeah, the angle bracket syntax is kind of ugly, but it's standard in C++, C# and Java, so even if you don't write code that uses it you're going to run into it all the time.

我真的没有看到创建这个类的任何价值,因为类名更易读。是的,尖括号语法有点难看,但它在 C++、C# 和 Java 中是标准的,所以即使你不编写使用它的代码,你也会一直遇到它。

回答by Darren Kopp

It's recommendedthat in public API's not to use List<T>, but to use Collection<T>

建议,在公共API不使用List <T>,而是利用收集<T>

If you are inheriting from it though, you should be fine, afaik.

如果你继承了它,你应该没问题,afaik。

回答by Ryan Eastabrook

I use generic lists for almost all scenarios. The only time that I would consider using a derived collection anymore is if I add collection specific members. However, the advent of LINQ has lessened the need for even that.

我几乎在所有场景中都使用通用列表。我唯一会考虑使用派生集合的时间是添加特定于集合的成员。然而,LINQ 的出现甚至减少了这种需求。

回答by Matt Hinze

this is the way:

这是方法:

return arrays, accept IEnumerable<T>

返回数组,接受 IEnumerable<T>

=)

=)