扩展列表< T>和违反打开/关闭原则 [英] Extending List<T> and Violating The Open/Closed Principle
问题描述
我刚刚创建在我的班级之一下面的方法。
I just created the following method in one of my classes
public static bool Assimilate(this List<Card> first, List<Card> second)
{
// Trivial
if (first.Count == 0 || second.Count == 0)
{
return false;
}
// Sort the lists, so I can do a binarySearch
first.Sort();
second.Sort();
// Copia only the new elements
int index;
for (int i = 0; i < second.Count; i++)
{
index = first.BinarySearch(second[i]);
if (index < 0)
{
first.Insert(~index, second[i]);
}
}
// Edit
second = null;
return true;
}
和我的一个朋友,审查我的代码,说我不应该创建'扩展列表类的方法,因为这违反了开/关的原则。
如果我想扩展类名单,我应该创建一个从名单继承一个新的类和实施新课改我的合并的方法。
是他吧?扩展List类违反了开放/关闭原则?
And a friend of mine, reviewing my code, said that I shouldn't create methods that 'extend the List class', since that violates the open/closed principle. If I want to extend the class List I should create a new class that inherits from List and implement my "merge" method in that new class. Is he right? Extending the List class violates the Open/Closed principle?
推荐答案
我不认为这违反了开/关的原则。我想想来讲,如果我要改变现有的代码将功能添加到一个对象,然后我违反打开/关闭,但延长的对象是你应该做到底该怎么添加功能。
I don't think this violates open/close principle. I think about it in terms of if I have to 'change' existing code to add functionality to an object then I'm violating open/close, but extending an object is exactly what you should do to add functionality.
您可以在不同的语言不同的方式扩展对象,继承只是一种方式; 。C#为您提供扩展方法添加到现有类的能力。
You can extend the object in different ways in different languages, inheritance is just one way; c# provides you the ability to add extension methods to an existing class.
记住'开放的扩展 - 关闭进行修改
Remember 'open for extension - close for modification'
这篇关于扩展列表< T>和违反打开/关闭原则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!