一个重载'+'的不可变列表是否有意义? [英] Does an immutable list that overloads '+' makes sense?

查看:76
本文介绍了一个重载'+'的不可变列表是否有意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它肯定不会脱离.NET框架的标准实践.当我看到a + b时,我总是假设会创建一些新内容.

It certainly does not break from the standard practice of the .NET framework. When I see a a + b I always assume something new will be created.

static void Main(string[] args)
{
    var list = BuildList(ImmutableList<int>.Empty);
    var sum = (list + 500).Sum();
    Console.WriteLine(sum);
    Console.ReadLine();
}

static ImmutableList<int> BuildList(ImmutableList<int> list)
{
    if (list.Count < 1000)
    {
        return BuildList(list + list.Count);
    }
    return list;
}

更新

有关如何在 令人惊讶的答复

我很惊讶地看到如此之多的答案,这是有道理的.原则上,我也同意,但是对于那些不太精简的人来说,阅读冗长的代码要比对精简的代码更容易.从我的工作经验来看,他们似乎占了大多数.

I am quite surprised to see so many answers that concur that this makes sense. In principle I also agree but it is way easier for me to read verbose code than it is for someone who is uncomfortable with terseness to read, well terse code. From my working experience they seem to be the majority.

推荐答案

我个人不建议对不应该视为原语的任何类重载像+这样的运算符.我认为,特别是集合绝对不能使运算符重载.

I personally would not recommend overloading operators like + for any class that isn't meant to be treated as a primitive. In particular, collections, in my opinion, should never overload operators.

当您的小型不可变类或结构的行为类似于原始"类型时,运算符重载才有意义.但是,当您开始尝试对其他类进行此操作时,确实会影响可维护性.

Operator overloading makes sense when you have a small immutable class or struct that is meant to behave like a "primitive" type. However, when you start trying to do this for other classes, it really impacts maintainability.

我建议改为进行显式方法调用.

I'd recommend making explicit method calls, instead.

阅读评论后,我的建议是使用Concat()(以匹配缺点(尽管缺点通常是前置的),使用法非常清楚:

After reading the comments, my recommendation would be to use Concat() (to match Enumerable.Concat in the Framework). Another option I would prefer would be Construct(), ala cons (though cons typically prepends), to make the usage very clear:

var list = BuildList(ImmutableList<int>.Empty);
var list2 = list.Concat(500); 
// Or: var list2 = list.Construct(500);

这篇关于一个重载'+'的不可变列表是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆