代码之家  ›  专栏  ›  技术社区  ›  Hazel へいぜる

扩展运算符是否有可能过载?

  •  0
  • Hazel へいぜる  · 技术社区  · 6 年前

    我最近拿到了约瑟夫和本·阿尔巴哈里写的一本C 7.0的简写本。当我浏览高级C一章时,特别是第199页,它开始涵盖运算符重载的地方;我开始想,是否有任何关于运算符重载的官方词汇,类似于至少对基元类型的扩展方法?例如:

    // Traditional Overload
    public static MyType operator +(MyType, MyType);
    
    // Traditional Extension Method
    public static int Sum(this int, int[]);
    
    // Possible Combination?
    public static int operator +(this int, int, string);
    

    在上面的示例中,加法运算符有传统的重载;这允许我自定义添加类型的属性,以便提供新的值。然后是传统的扩展方法,我们可以通过添加我们认为有用的方法来扩展类型;类似于上面的例子,如果我经常在一个整型数组中执行所有值的加法以得到它们的和,那么我可以创建一个有用的扩展方法to实施:

    int sum = int.Sum(myArrayOfIntegers);
    

    有了所有这些,扩展操作符重载可能是有用的,至少对于原语是如此。例如:

    public static int operator +(this int i, int x, string y) {
        // Perform parsing of the string and return the newly added value between x and y.
    }
    

    然后我可以在多个有用的基元类型上执行算术,并且不必经常尝试解析代码中的数据。这并不是说解析数据很困难,但是当你要做数百次相同的事情(包括调用一个方法来执行解析和算术)时,如果有什么事情的话,它可能会变得单调乏味。

    我做了一些调查,从那以后就找不到与这个话题有关的任何东西了。 this post 在2008年得到了答复。十年是很长的一段时间,我希望那篇文章的观点从那时起已经改变了。

    很抱歉,我们将在下一个版本中不执行此操作。在我们的计划中,我们确实非常重视扩展成员,并花了大量的精力试图使他们正确,但最终我们无法使它足够顺利,并决定让位给其他有趣的功能。

    这仍然是我们的雷达上的未来版本。如果我们有大量令人信服的场景,可以帮助推动正确的设计,这将有所帮助。

    在我看来,在我们的雷达上仍然不是很有前途。

    请仅在资源可靠且目前(或前2年内)的情况下提供答案。

    1 回复  |  直到 6 年前
        1
  •  1
  •   AustinWBryan ravenspoint    6 年前

    是的。在C 8中,很可能会有“扩展一切”的解释。 here 在Github上。

    “扩展一切”包括:

    • 扩展静态字段
    • 扩展静态方法
    • 扩展静态属性
    • 扩展属性
    • 扩展索引器
    • 延伸铸造
    • 扩展运算符

    不包括:

    • 扩展实例字段(首先)
    • 扩展构造函数(首先)
    • 扩展事件(首先)
    • 扩展自动属性(直到它们支持扩展实例字段)

    语法可能如下所示:

    public extension class List2DExt<T> : List<List<T>> 
    {
        // Extension static field
        private static int _flattenCount = 0;
    
        // Extension static property
        public static int FlattenCount => _flattenCount;
    
        // Extension static method
        public static int Get FlattenCount() => _flattenCount;
    
        // New syntax for extension methods
        public List<T> Flatten() { ... }
    
        // Extension indexers
        public List<List<T>> this[int[] indices] => ...;
    
        // Extension implicit operator
        public static implicit operator List<T>(List<List<T>> self) => self.Flatten();
    
        // Extension operator overload
        public static implicit List<List<T>> operator +(List<List<T>> left, List<List<T>> right) => left.Concat(right);
    }
    

    实例字段最初不受支持的原因是与它们如何跟踪这些字段的状态有关,我想这很棘手。