【问题标题】:Why can't I define the "+" operator for IEnumerable<T>? [duplicate]为什么我不能为 IEnumerable<T> 定义“+”运算符? [复制]
【发布时间】:2020-01-27 12:00:13
【问题描述】:

这不是一个问题(但请参阅帖子底部)。只是为了好玩 - 只是我接受了新的 C# 功能的培训。
Haskell 与 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 定义“+”运算符 - 这样代码会更紧凑(请参阅代码底部的注释行)。
这很有趣——为什么? - 这可能是我的问题。

【问题讨论】:

  • 看起来很有趣,但我建议您将其发布到 stackexchange (codereview)
  • 谢谢!我不知道“stackexchange”的存在。
  • 通常,如果代码不能正常工作,您会将其发布到 SO,但如果您想改进您的工作代码并寻找使代码变得更好的人,您可以将其发布到 codereview。很高兴我能帮上忙
  • 这不适用于代码审查。您的问题的简单答案是您不能在类型定义之外定义运算符。当团队实现extension function members 时,它可能是可能的。
  • 如果您编写了IEnumerable&lt;T&gt; 类型并且它不是接口,那么显然您可以自己添加重载运算符。所以你的问题真的是问为什么你不能扩展你无法控制的类型——即为它写一个扩展方法。有关详细信息,请参阅标记的重复项。

标签: c# c#-8.0


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2018-03-16
    • 2015-11-13
    • 2011-04-13
    相关资源
    最近更新 更多