加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 扩展列表并违反开放/封闭原则

发布时间:2020-12-15 04:08:30 所属栏目:百科 来源:网络整理
导读:我刚刚在我的一个类中创建了以下方法 public static bool Assimilate(this ListCard first,ListCard second){ // Trivial if (first.Count == 0 || second.Count == 0) { return false; } // Sort the lists,so I can do a binarySearch first.Sort(); secon
我刚刚在我的一个类中创建了以下方法
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类’的方法,因为这违反了开放/封闭原则.
如果我想扩展类List,我应该创建一个继承自List的新类,并在该新类中实现我的“merge”方法.
他是对的吗?扩展List类违反了开放/封闭原则?

解决方法

我不认为这违反了开/关原则.我考虑的是,如果我必须“更改”现有代码以向对象添加功能,那么我违反了打开/关闭,但扩展对象正是您应该做的添加功能.

你可以用不同的语言以不同的方式扩展对象,继承只是一种方式; c#使您能够将扩展方法添加到现有类.

记住’开放扩展 – 关闭修改’

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读