使用List< T>的C#运算符重载; [英] C# operator overloading with List<T>

查看:118
本文介绍了使用List< T>的C#运算符重载;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

,因此"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.

(顺便说一下,这是Systems.Collections.Generic中的List类.)

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

推荐答案

据我所知,这是不可行的:您必须以使用它的类型来实现操作符重载.由于List<T>不是您的类型,因此您不能覆盖其中的运算符.

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.

但是,您可以从List<string>派生自己的类型,并在类中覆盖运算符.

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) {
    }
}

这篇关于使用List&lt; T&gt;的C#运算符重载;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆