有没有办法在C#中重载+ =运算符

Eon*_*Eon 0 c# operator-overloading

我试图+=在我的c#代码中重载一个运算符,基本上只是为了keyValuePair给a 添加一个结构Hashtable(在这种情况下,它是一个继承自HashtableClass的类)

using System;
using System.Collections.Generic;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Program
{
    private static void Main()
    {
        var x = new HashClass();
        x.Add("one", "one");
        x.Add("two", "two");

        var y = x + new KeyValuePair<string, string>("three", "three");
        y += new KeyValuePair<string, string>("four", "four");

        foreach (System.Collections.DictionaryEntry z in y)
        {
            Console.WriteLine(z.Key + " " + z.Value);
        }
    }
}

public class HashClass : System.Collections.Hashtable
{
    public static System.Collections.Hashtable operator +(HashClass itema, KeyValuePair<string, string> itemb)
    {
        itema.Add(itemb.Key, itemb.Value);
        return itema;
    }

    public static System.Collections.Hashtable operator +=(HashClass itema, KeyValuePair<string, string> itemb)
    {
        itema.Add(itemb.Key, itemb.Value);
        return itema;
    }

    public static implicit operator HashClass(KeyValuePair<string, string> item)
    {
        var x = new HashClass();
        x.Add(item.Key, item.Value);
        return x;
    }
}
Run Code Online (Sandbox Code Playgroud)

弹出以下错误:

  1. 期望可重载的二元运算符(我认为+ =是一个有效的运算符.是否附加了特殊规则?
  2. 运算符"+ ="不能应用于'Hashtable'和'KeyValuePair'类型的操作数 - 这种方法很有意义.我y已经隐含地将其转换为Hashtable.作为一个理论,我认为这部分将失败,因为y它不是HashClass

还有什么可以尝试重载+ =运算符?这甚至可能吗?

Sel*_*enç 6

你只需要重载+运算符,因为+=它只是一个语法糖,例如:

x += 1
Run Code Online (Sandbox Code Playgroud)

相当于

x = x + 1;
Run Code Online (Sandbox Code Playgroud)

  • @hvd那么这只是意味着为哈希表重载运算符不是一个好主意. (2认同)