【问题标题】:C# operator overloading with List<T>使用 List<T> 进行 C# 运算符重载
【发布时间】:2012-02-04 17:44:24
【问题描述】:

我试图在 C# 中重载一个适用于 Lists 的运算符(不要问为什么!)。例如,我希望能够写:

List<string> x = // some list of things
List<string> y = // some list of things
List<string> z = x + y

所以'z'包含'x'的所有内容,然后是'y'的内容。我知道已经有组合两个列表的方法,我只是想了解运算符重载如何与泛型结构一起工作。

(顺便说一下,这是来自Systems.Collections.GenericList 类。)

【问题讨论】:

  • List 在您的示例中是您自己的实现吗?还是来自System.Collections.Generic 命名空间?
  • 来自 System.Collections.Generic。

标签: c# operator-overloading


【解决方案1】:

据我所知,这是不可行的:您必须在使用它的类型中实现运算符重载。由于List&lt;T&gt; 不是您的类型,因此您不能覆盖其中的运算符。

但是,您可以从 List&lt;string&gt; 派生您自己的类型,并覆盖您的类中的运算符。

class StringList : List<string> {
    public static StringList operator +(StringList lhs, StringList rhs) {
    }
}

【讨论】:

  • 不要忘记运算符是根据编译时类型选择的。所以List&lt;string&gt; a = new StringList(), b = new StringList(); var c = a + b 行不通。
  • @svick 你是绝对正确的,不可能欺骗编译器以某种方式接受你的操作数上的操作数,这些操作数不是静态类型为你定义运算符的类.
  • 那么为什么我可以重载* 以使用Strings,而不是List&lt;String&gt;s?
  • @Joe 如何覆盖* 以使用Strings? Eric Lippert from the C# compiler team says you cannot overload operators of Strings。你能提供一些代码吗?这可能值得自己提出问题。
猜你喜欢
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 2016-02-19
  • 1970-01-01
相关资源
最近更新 更多