如何在C#中扩展KeyValuePair stuct运算符?

Ire*_*311 0 c# struct operator-overloading keyvaluepair

假设我有两个KeyValuePair变量.

     KeyValuePair<string, double> kv1 = new KeyValuePair<string, double>("a", 5);
     KeyValuePair<string, double> kv2 = new KeyValuePair<string, double>("b", 7);
Run Code Online (Sandbox Code Playgroud)

"KeyValuePair"结构中没有+ operation的定义.
所以我想使用运算符重载!

我的目标是获得第三个KeyValuePair类型变量,如:

  KeyValuePair<string, double> kv1 = new KeyValuePair<string, double>(kv1.Key + " + " + kv2.Key, kv1.Value + kv2.Value);
Run Code Online (Sandbox Code Playgroud)

结果将是:

KeyValuePair<string, double>("a + b", 12)
Run Code Online (Sandbox Code Playgroud)

但是告诉我如何使用"运营商"来做到这一点?

我试图这样做:

public partial class Form1 : Form
{ 
    public Form1()
    {
     KeyValuePair<string, double> kv1 = new KeyValuePair<string, double>("a", 5);
     KeyValuePair<string, double> kv2 = new KeyValuePair<string, double>("b", 7);

     KeyValuePair<string, double> k = kv1 + kv2;
    }
    public static KeyValuePair<string, double> operator +(KeyValuePair<string, double> c1, KeyValuePair<string, double> c2) => new KeyValuePair<string, double>(c1.Key + " + " + c2.Key, c1.Value + c2.Value);
}
Run Code Online (Sandbox Code Playgroud)

但是有一条错误消息:"至少有一个参数应该是Form1"

这意味着你只能为Form.From1输入创建运算符......我想扩展KeyValuePair类!
但后来我介绍说"KeyValuePair"是一个结构但它不是一个类!

我们可以创建继承自"KeyValuePair"结构的新结构吗?

那怎么办呢?
谢谢!

ang*_*son 5

你不能做这个.

无法将运算符添加到其他类型,您必须所涉及的类型中添加它们.

你能做的最好的事情就是创建一个扩展方法或者只是一个普通的方法.

但是,扩展方法也不容易,因为您无法访问泛型方法中泛型类型的运算符.

扩展方法示例不起作用:

public static class MyKeyValuePairExtensions
{
    public static KeyValuePair<TKey, TValue> Add<TKey, TValue>(
        this KeyValuePair<TKey, TValue> first,
        KeyValuePair<TKey, TValue> second)
    {
        return new KeyValuePair<TKey, TValue>(
            first.Key + second.Key,
            first.Value + second.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将无法编译:

CS0019运算符'+'不能应用于'TKey'和'TKey'类型的操作数

现在,你可以添加各种第三方nuget软件包,让你模拟这个,但我将把它作为阅读器的练习.

另一种选择是为您的特定情况添加扩展方法:

public static class MyKeyValuePairExtensions
{
    public static KeyValuePair<string, double> Add(
        this KeyValuePair<string, double> first,
        KeyValuePair<string, double> second)
    {
        return new KeyValuePair<string, double>(
            first.Key + " + " + second.Key,
            first.Value + second.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你会这样称呼它:

KeyValuePair<string, double> kv1 = new KeyValuePair<string, double>("a", 5);
KeyValuePair<string, double> kv2 = new KeyValuePair<string, double>("b", 7);
var sum = kv1.Add(kv2); Key="a + b", and Value=12
Run Code Online (Sandbox Code Playgroud)

这是一个试验的.NET小提琴.