简体   繁体   English

从索引器返回IEnumerable,不好的做法吗?

[英]Returning IEnumerable from an indexer, bad practice?

If I had a CarsDataStore representing a table something like: 如果我有一个CarsDataStore代表一个表,例如:

Cars
--------------
Ford | Fiesta
Ford | Escort
Ford | Orion
Fiat | Uno
Fiat | Panda

Then I could do 那我就可以

IEnumerable<Cars> fords = CarsDataStore["Ford"];

Is this a bad idea? 这是一个坏主意吗? It's inconsistent with the other datastore objects in my api (which all have a single column PK indexer), and I'm guessing most people don't expect an indexer to return a collection in this situation. 它与我的api中的其他数据存储对象(均具有单个列PK索引器)不一致,并且我猜大多数人不希望索引器在这种情况下返回集合。

Yes, i think it's a bad idea, specially, if it's inconsistent with the rest of the api. 是的,我认为这是个坏主意,特别是如果它与其他api不一致。 Consistency is a key thing and you should always strive to be consistent. 一致性是关键,您应该始终保持一致。

I wouldn't expect an indexer to return a collection but then the compiler would tell me that if I ran into any problems. 我不希望索引器返回一个集合,但是编译器会告诉我,如果遇到任何问题。

However I would personally implement something more along the lines of 但是,我个人会按照

IEnumerable<Cars> fords = CarsDataStore.GetCarsByType("Ford");

Change your primary data structure and your issue goes away (syntax probably isn't perfect): 更改主数据结构,问题就消失了(语法可能并不完美):

Dictionary<string, List<string>> cars =
    new Dictionary<string, List<string>>();

cars.Add("Ford", { "Fiesta", "Escort", "Orion" });
cars.Add("Fiat", { "Uno", "Panda" });

IEnumerable<string> fordCars = cars["Ford"];

Of course, you would have to change string to Car , but the idea would be the same. 当然,您必须将string更改为Car ,但是想法是相同的。

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

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