当前位置: 代码迷 >> C# >> 请教怎么重载+=运算符
  详细解决方案

请教怎么重载+=运算符

热度:377   发布时间:2016-05-05 03:52:56.0
请问如何重载+=运算符?
有2个问题不明白

1. + 运算符可以重载,但是好像不能重载+=

2. 重载只能写在+ 两边任意一个的类中,例如要实现  cat + dog,就只能写在cat类或者dog类中,那么像list<string> + list<string>或者list<cat> + list<dog>这种怎么做?


谢谢
------解决思路----------------------
1、+=不就是+号和=号么?
2、泛型不能重载,不过貌似版主知道通过反射方法实现
------解决思路----------------------
+= 本来就不是运算符,它是c#语法糖。
------解决思路----------------------
如果要变通,我给你写一个例子
public class MyListOfString
{
    public List<string> Contents;

    public static List<string> operator +(MyListOfString a, List<string> b)
    {
        return a.Contents.Concat(b).ToList();
    }

    public static implicit operator MyListOfString(List<string> a)
    {
        return new MyListOfString { Contents = a };
    }
}


那么对于两个 List<string>,你可以这样连接
var a = new List<string> { "aa" };
var b = new List<string> { "bb" };
var result = (MyListOfString)a + b;
  相关解决方案