Eon*_*Eon 0 c# operator-overloading
我试图+=
在我的c#代码中重载一个运算符,基本上只是为了keyValuePair
给a 添加一个结构Hashtable
(在这种情况下,它是一个继承自Hashtable
Class的类)
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)
弹出以下错误:
y
已经隐含地将其转换为Hashtable.作为一个理论,我认为这部分将失败,因为y
它不是HashClass还有什么可以尝试重载+ =运算符?这甚至可能吗?
你只需要重载+
运算符,因为+=
它只是一个语法糖,例如:
x += 1
Run Code Online (Sandbox Code Playgroud)
相当于
x = x + 1;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
314 次 |
最近记录: |