繁体   English   中英

C#重载泛型+运算符

[英]C# Overload generic + operator

我正在尝试通过将项目添加到列表中来添加列表。

我试图实现的目标代码使用:

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

我尝试过的 “运算符+”应重载+,“此IList”应扩展通用IList。

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

但是它不起作用,在Visual Studios 2012中,红色强调了它的位置。我在做什么错? 这不可能吗? 为什么这对于标准类而不对通用类有效?

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

同样,至少一个参数必须与该类具有相同的类型。

因此,您可以做的最好的事情是:

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#中的重载+运算符”中进行搜索会把它显示为最佳结果。 它可能会帮助某人。

void Main()
{
    List<string> str = new List<string> {"one", "two", "three"};
    List<string> obj = new List<string> {"four", "five", "six", "seven"};
    foreach ( string s in str + obj ) Console.Write(s + ", ");
}

public class List<T> : System.Collections.Generic.List<T> 
{

    public static List<T> operator +(List<T> L1, List<T> L2)
    {
        List<T> tmp = new List<T>() ;
        foreach ( T s in L1 ) tmp.Add(s);
        foreach ( T s in L2 ) tmp.Add(s);
        return tmp ; 
    }
}

//one, two, three, four, five, six, seven,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM