C#重载泛型+运算符 [英] C# Overload generic + operator

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

问题描述

我正在尝试通过在其中添加项目来使列表能够添加到其中.

I'm trying to make a list be able to added to by plusing an item into it.

我要实现的目标代码使用:

Target use of code I'm trying to make happen:

List<int> numbers = new List<int>();
numbers += 10;

我尝试过的.运算符+"应重载+,此IList"应扩展通用IList.

What I've tried. "operator +" should overload + and "this IList" should extend generic IList.

public static IList<T> operator +<T>(this IList<T> list, T element)
{
    list.Add(element);
    return list;
}

但是它不起作用,在Visual Studio 2012中,红色强调了它的各处.我究竟做错了什么?这不可能吗?为什么这对标准类却不能对通用类起作用?

It's not working however, red underlines everywhere over it in visual studios 2012. What am I doing wrong? Is this not possible? Why could this work for a standard class but not a generic class?

推荐答案

只能在类的定义中重载运算符.您无法使用扩展方法从外部覆盖它们.

Operators can only be overloaded in the definition of the class. You can't override them from outside by using extension methods.

此外,至少一个参数必须与该类具有相同的类型.

Also, at least one of the parameters must be of the same type as the class.

所以您能做的最好的事情是:

So the best you can do is something like:

public class CustomList<T> : List<T>
{
    public static CustomList<T> operator +(CustomList<T> list, T element)
    {
        list.Add(element);
        return list;
    }
}

然后您可以像这样使用

var list = new CustomList<int> { 1, 2 };

list += 3;

Console.WriteLine(string.Join(", ", list)); // Will print 1, 2, 3

这篇关于C#重载泛型+运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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