本文介绍了我如何知道何时创建接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正处于开发学习阶段,我觉得我必须更多地了解界面.

I'm at a point in my development learning where I feel like I must learn more about interfaces.

我经常阅读它们,但似乎我无法理解它们.

I frequently read about them but it just seems like I cannot grasp them.

我读过这样的例子:Animal 基类,带有 IAnimal 接口,用于诸如Walk"、Run"、GetLegs"等之类的东西 - 但我从来没有做过一些事情,感觉就像嘿,我应该在这里使用一个接口!"

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

我错过了什么?为什么这个概念对我来说很难把握!我只是害怕我可能永远不会意识到对一个的具体需求 - 主要是由于理解它们的某些方面的缺失!这让我觉得我在成为一名开发人员方面缺少一些最重要的东西!如果有人有过这样的经历并取得了突破,我会很感激一些关于如何理解这个概念的提示.谢谢.

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

推荐答案

它解决了这个具体问题:

it solves this concrete problem:

您有 4 种不同类型的 a、b、c、d.在你的代码中,你有类似的东西:

you have a, b, c, d of 4 different types. all over your code you have something like:

a.Process();
b.Process();
c.Process();
d.Process();

为什么不让他们实现 IProcessable,然后再做

why not have them implement IProcessable, and then do

List<IProcessable> list;

foreach(IProcessable p in list)
    p.Process();

当你添加,比如说,50 种类型的类都做同样的事情时,这会更好地扩展.

this will scale much better when you add, say, 50 types of classes that all do the same thing.

另一个具体问题:

你看过 System.Linq.Enumerable 吗?它定义了大量的扩展方法,可以对实现 IEnumerable 的任何类型进行操作.因为任何实现 IEnumerable 的东西基本上都说我支持无序 foreach 类型模式中的迭代",所以您可以为任何可枚举类型定义复杂的行为(Count、Max、Where、Select 等).

Have you ever taken a look at System.Linq.Enumerable? It defines a ton of extension methods that operate on any type that implements IEnumerable. Because anything that implements IEnumerable basically says "I support iteration in a unordered foreach-type pattern", you can define complex behaviors (Count, Max, Where, Select, etc.) for any enumerable type.

这篇关于我如何知道何时创建接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 06:36