我将如何知道何时创建界面? [英] How will I know when to create an interface?
问题描述
我经常阅读关于他们,但它似乎就像我无法掌握它们。
我已经阅读了例子:动物基类,IAnimal接口,例如Walk,Run,GetLegs等 - 但我从来没有在做过某些事情,觉得嘿,我应该在这里使用界面。
我失踪了什么?为什么这么难的概念让我掌握!我只是因为我可能没有意识到一个具体的需要 - 主要是由于一些缺乏认识的方面的事实而被吓倒!这让我觉得我在开发商方面缺少一些顶点的东西!如果任何人有这样的经历,并且有一个突破,我会欣赏一些关于如何理解这个概念的技巧。谢谢。
它解决了这个具体问题:
你具有4种不同类型的a,b,c,d。你的代码全部都是这样的:
a.Process();
b.Process();
c.Process();
d.Process();
为什么不让他们实现IP可处理,然后执行
列表< IProcessable>列表;
foreach(列表中的IProcessable p)
p.Process();
当你添加50个类,所有这些都做同样的事情
另一具体问题:
看看System.Linq.Enumerable?它定义了大量的实现IEnumerable的任何类型的扩展方法。因为任何实现IEnumerable的东西基本上都说我以无序的foreach类型模式支持迭代,你可以为任何可枚举类型定义复杂的行为(Count,Max,Where,Select等)。
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.
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:
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();
why not have them implement IProcessable, and then do
List<IProcessable> list;
foreach(IProcessable p in list)
p.Process();
this will scale much better when you add, say, 50 types of classes that all do the same thing.
Another concrete problem:
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.
这篇关于我将如何知道何时创建界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!