C# operator overloading with List

2019-06-19 20:45发布

I'm trying to overload an operator in C# (don't ask why!) that applies to Lists. For example, I'd like to be able to write:

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

so that 'z' contains all the contents of 'x' followed by the contents of 'y'. I'm aware that there are already ways to combine two lists, I'm just trying to understand how operator overloading works with generic structures.

(This is the List class from Systems.Collections.Generic, by the way.)

1条回答
Root(大扎)
2楼-- · 2019-06-19 21:38

As far as I know, this is not doable: you must implement the operator overload in the type that uses it. Since List<T> is not your type, you cannot override operators in it.

However, you can derive your own type from List<string>, and override the operator inside your class.

class StringList : List<string> {
    public static StringList operator +(StringList lhs, StringList rhs) {
    }
}
查看更多
登录 后发表回答