为什么不能为IEnumerable <T>定义“ +”运算符?

时间:2019-09-27 07:28:20

标签: c# c#-8.0

这不是问题(但是请参阅文章底部)。只是为了好玩-我接受了C#新功能的培训。
Haskell vs C#8.0:)

static class CS8_Tests
{
    public static void Deconstruct<T>(this IEnumerable<T> items, out T head, out IEnumerable<T> tail)
        => (head, tail) = (items.FirstOrDefault(), items.Skip(1));

    /// <summary>
    /// Famous Haskell implementation:
    /// quicksort :: (Ord a) => [a] –> [a]
    /// quicksort[] = []
    /// quicksort(x:xs) =
    /// let smallerSorted = quicksort[a | a <– xs, a <= x]
    ///     biggerSorted  = quicksort[a | a <– xs, a >  x]
    /// in smallerSorted ++ [x] ++ biggerSorted
    /// </summary>
    static IEnumerable<T> quickSort<T>(IEnumerable<T> items) where T : IComparable<T>
        => items switch
        {
            _ when items.Count() == 0 => items,
            (var x, var xs) => quickSort(xs.Where(a => a.CompareTo(x) <= 0))
                              .Append(x)
                              .Concat(quickSort(xs.Where(a => a.CompareTo(x) > 0)))
        };

    static int indexOf<T>(IEnumerable<T> items, T target, int index = 0) where T : IEquatable<T>
        => items switch
        {
            (var h, _) when h.Equals(target) => index,
            (_, var tail) when tail.Count() == 0 => -1,
            (_, var tail) => indexOf(tail, target, index + 1),
        };

    public static void RunTests()
    {
        var items = new List<int> { 2, 5, 7, 5, 1, 4, 3, 1 };
        var sorted_items = quickSort(items).ToList();
        var index = indexOf(items, 1);
    }

    //public static IEnumerable<T> operator +(IEnumerable<T> elms1, IEnumerable<T> elms2)
    //    => elms1.Concat(elms2);   
}

不幸的是,我们无法为IEnumerable定义“ +”运算符-否则此代码将更加紧凑(请参见代码底部的注释行)。
有趣的是-为什么? -这可能是我的问题。

1 个答案:

答案 0 :(得分:0)

简短的答案是因为您不能在接口上定义运算符,并且C#不支持扩展运算符。

关于为什么没有添加它,更长的答案是因为没有免费的东西。设计,记录,实施,测试,发布和支持功能需要花费时间(因此也要花钱)。我的猜测是,由于复杂性,这一(扩展运算符)的成本要高于其他类似/更高价值的功能。

相关问题