Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c# - 为什么不从列表继承 <T> ?(Why not inherit from List<T>?)

When planning out my programs, I often start with a chain of thought like so:

(在计划程序时,我通常会像这样思考:)

A football team is just a list of football players.

(足球队只是足球运动员的名单。)

Therefore, I should represent it with:

(因此,我应该用:)

 var football_team = new List<FootballPlayer>(); 

The ordering of this list represent the order in which the players are listed in the roster.

(该列表的顺序代表了在名单中列出球员的顺序。)

But I realize later that teams also have other properties, besides the mere list of players, that must be recorded.

(但是后来我意识到,除了球员名单外,球队还有其他属性,必须加以记录。)

For example, the running total of scores this season, the current budget, the uniform colors, a string representing the name of the team, etc..

(例如,本赛季的总得分,当前预算,统一的颜色,代表球队名称的string等。)

So then I think:

(所以我想:)

Okay, a football team is just like a list of players, but additionally, it has a name (a string ) and a running total of scores (an int ).

(好的,一支足球队就像一个球员名单,但是另外,它还有一个名字( string )和总得分(一个int )。)

.NET does not provide a class for storing football teams, so I will make my own class.

(.NET没有提供用于存储足球队的课程,因此我将创建自己的课程。)

The most similar and relevant existing structure is List<FootballPlayer> , so I will inherit from it:

(最相似和相关的现有结构是List<FootballPlayer> ,所以我将从它继承:)

 class FootballTeam : List<FootballPlayer> { public string TeamName; public int RunningTotal } 

But it turns out that a guideline says you shouldn't inherit from List<T> .

(但事实证明, 有一条准则规定您不应从List<T>继承 。)

I'm thoroughly confused by this guideline in two respects.

(我对该指南在两个方面完全感到困惑。)

Why not? (为什么不?)

Apparently List is somehow optimized for performance .

(显然List在某种程度上针对性能进行了优化 。)

How so?

(怎么会这样?)

What performance problems will I cause if I extend List ?

(如果我扩展List会导致什么性能问题?)

What exactly will break?

(到底会破裂什么?)

Another reason I've seen is that List is provided by Microsoft, and I have no control over it, so I cannot change it later, after exposing a "public API" .

(我看到的另一个原因是List由Microsoft提供,并且我无法控制它,因此以后在公开“ public API”之后就无法更改它 。)

But I struggle to understand this.

(但是我很难理解这一点。)

What is a public API and why should I care?

(什么是公共API,我为什么要关心?)

If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline?

(如果我当前的项目没有并且不太可能拥有此公共API,那么我可以安全地忽略此指南吗?)

If I do inherit from List and it turns out I need a public API, what difficulties will I have?

(如果我确实从List继承而来但事实证明我需要一个公共API,我会遇到什么困难?)

Why does it even matter?

(为什么如此重要?)

A list is a list.

(列表就是列表。)

What could possibly change?

(有什么可能改变?)

What could I possibly want to change?

(我可能要更改什么?)

And lastly, if Microsoft did not want me to inherit from List , why didn't they make the class sealed ?

(最后,如果Microsoft不希望我从List继承,他们为什么不将类sealed ?)

What else am I supposed to use? (我还应该使用什么?)

Apparently, for custom collections, Microsoft has provided a Collection class which should be extended instead of List .

(显然,对于自定义集合,Microsoft提供了Collection类,应该扩展该类而不是List 。)

But this class is very bare, and does not have many useful things, such as AddRange , for instance.

(但是此类非常裸露,并且没有很多有用的东西, 例如AddRange 。)

jvitor83's answer provides a performance rationale for that particular method, but how is a slow AddRange not better than no AddRange ?

(jvitor83的答案提供了该特定方法的性能原理,但是慢速AddRange怎么比没有AddRange更好呢?)

Inheriting from Collection is way more work than inheriting from List , and I see no benefit.

(从Collection继承要比从List继承做更多的工作,我看不出任何好处。)

Surely Microsoft wouldn't tell me to do extra work for no reason, so I can't help feeling like I am somehow misunderstanding something, and inheriting Collection is actually not the right solution for my problem.

(当然,Microsoft不会无缘无故地告诉我做额外的工作,因此我不禁感到自己在某种程度上误解了某些东西,而继承Collection实际上不是解决我问题的正确方法。)

I've seen suggestions such as implementing IList .

(我已经看到了实现IList建议。)

Just no.

(就是不行。)

This is dozens of lines of boilerplate code which gains me nothing.

(这是几十行样板代码,对我毫无帮助。)

Lastly, some suggest wrapping the List in something:

(最后,有些人建议将List包装在以下内容中:)

class FootballTeam 
{ 
    public List<FootballPlayer> Players; 
}

There are two problems with this:

(这有两个问题:)

  1. It makes my code needlessly verbose.

    (它使我的代码不必要地冗长。)

    I must now call my_team.Players.Count instead of just my_team.Count .

    (我现在必须调用my_team.Players.Count而不是my_team.Count 。)

    Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal List ... But that's a lot of code!

    (幸运的是,使用C#,我可以定义索引器以使索引透明化,并转发内部List所有方法...但是,这需要很多代码!)

    What do I get for all that work?

    (我能从所有工作中得到什么?)

  2. It just plain doesn't make any sense.

    (只是没有任何意义。)

    A football team doesn't "have" a list of players.

    (一支足球队没有“拥有”球员名单。)

    It is the list of players.

    (这球员名单。)

    You don't say "John McFootballer has joined SomeTeam's players".

    (您不会说“ John McFootballer已加入SomeTeam的球员”。)

    You say "John has joined SomeTeam".

    (您说“约翰加入了SomeTeam”。)

    You don't add a letter to "a string's characters", you add a letter to a string.

    (您没有在“字符串的字符”中添加字母,而是在字符串中添加了字母。)

    You don't add a book to a library's books, you add a book to a library.

    (您没有将书添加到图书馆的书中,而是将书添加到图书馆。)

I realize that what happens "under the hood" can be said to be "adding X to Y's internal list", but this seems like a very counter-intuitive way of thinking about the world.

(我意识到,“幕后”发生的事情可以说是“将X添加到Y的内部列表中”,但这似乎是一种非常反常的思考世界的方式。)

My question (summarized) (我的问题(总结))

What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?

(什么是C#表示数据结构的正确方法,“逻辑上”(也就是说,“对人类而言”)只是一小部分thingslist ?)

Is inheriting from List<T> always unacceptable?

(从List<T>继承始终是不可接受的吗?)

When is it acceptable?

(什么时候可以接受?)

Why/why not?

(为什么/为什么不呢?)

What must a programmer consider, when deciding whether to inherit from List<T> or not?

(程序员在决定是否从List<T>继承时必须考虑什么?)

  ask by Superbest translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are some good answers here.

(这里有一些很好的答案。)

I would add to them the following points.

(我将向他们补充以下几点。)

What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?

(什么是C#表示数据结构的正确方法,“逻辑上”(也就是说,“对人类而言”)只是一小部分东西的清单?)

Ask any ten non-computer-programmer people who are familiar with the existence of football to fill in the blank:

(让任何十位熟悉足球存在的非计算机编程人员来填补空白:)

A football team is a particular kind of _____

Did anyone say "list of football players with a few bells and whistles", or did they all say "sports team" or "club" or "organization"?

(有人说过“有几分风吹草动的足球运动员名单”,还是他们都说过“运动队”或“俱乐部”或“组织”?)

Your notion that a football team is a particular kind of list of players is in your human mind and your human mind alone.

(您认为足球队是一种特殊的球员名单,这在您的人心中和您的人心中都是存在的。)

List<T> is a mechanism .

(List<T>是一种机制 。)

Football team is a business object -- that is, an object that represents some concept that is in the business domain of the program.

(足球队是一个业务对象 ,即代表该程序业务领域中某些概念的对象。)

Don't mix those!

(不要混那些!)

A football team is a kind of team;

(足球队是一种球队。)

it has a roster, a roster is a list of players .

(它有一个名册,一个名册是一个球员名单 。)

A roster is not a particular kind of list of players .

(名册不是特定的球员名单 。)

A roster is a list of players.

(名册球员名单。)

So make a property called Roster that is a List<Player> .

(因此,使一个名为Roster的属性成为List<Player> 。)

And make it ReadOnlyList<Player> while you're at it, unless you believe that everyone who knows about a football team gets to delete players from the roster.

(并在使用时将其设置为ReadOnlyList<Player> ,除非您认为知道足球队的每个人都将从名单中删除球员。)

Is inheriting from List<T> always unacceptable?

(从List<T>继承始终是不可接受的吗?)

Unacceptable to who?

(谁不能接受?)

Me?

(我?)

No.

(没有。)

When is it acceptable?

(什么时候可以接受?)

When you're building a mechanism that extends the List<T> mechanism .

(在构建扩展List<T>机制的机制时 。)

What must a programmer consider, when deciding whether to inherit from List<T> or not?

(程序员在决定是否从List<T>继承时必须考虑什么?)

Am I building a mechanism or a business object ?

(我是在建立机制还是业务对象 ?)

But that's a lot of code!

(但这是很多代码!)

What do I get for all that work?

(我能从所有工作中得到什么?)

You spent more time typing up your question that it would have taken you to write forwarding methods for the relevant members of List<T> fifty times over.

(您花了更多时间输入问题,这将使您为List<T>的相关成员编写转发方法超过50次。)

You're clearly not afraid of verbosity, and we are talking about a very small amount of code here;

(您显然不怕冗长,在这里我们谈论的代码很少。)

this is a few minutes work.

(这是几分钟的工作。)

UPDATE (更新)

I gave it some more thought and there is another reason to not model a football team as a list of players.

(我再三考虑一下,还有另一个原因不将足球队建模为球员名单。)

In fact it might be a bad idea to model a football team as having a list of players too.

(实际上,将足球队建模为也球员名单可能不是一个好主意。)

The problem with a team as/having a list of players is that what you've got is a snapshot of the team at a moment in time .

(拥有/拥有队员列表的球队存在的问题是,您所拥有的只是某个时刻快照 。)

I don't know what your business case is for this class, but if I had a class that represented a football team I would want to ask it questions like "how many Seahawks players missed games due to injury between 2003 and 2013?"

(我不知道您在这堂课上的业务案例是什么,但是如果我有一堂代表足球队的课,我想问一下这样的问题:“有多少海鹰球员因2003年至2013年受伤而缺席比赛?”)

or "What Denver player who previously played for another team had the largest year-over-year increase in yards ran?"

(还是“以前为另一支球队效力的丹佛球员在码数上的同比增长最大?”)

or " Did the Piggers go all the way this year? "

(或“ 今年猪头人一路走? ”)

That is, a football team seems to me to be well modeled as a collection of historical facts such as when a player was recruited, injured, retired, etc. Obviously the current player roster is an important fact that should probably be front-and-center, but there may be other interesting things you want to do with this object that require a more historical perspective.

(就是说,在我看来,一支足球队的模型被很好地模拟为历史事实的集合,例如球员被招募,受伤,退休等的历史事实 。显然,目前的球员名册是一个重要的事实,应该很重要。居中,但您可能还需要对这个对象进行其他有趣的操作,这些操作需要更多的历史视角。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...