在C#中如何自定义字典的键类型

1949idc 2年前 (2024-09-19) 阅读数 304 #编程语言

在C#中,要自定义字典的键类型,您需要创建一个自定义类并实现IEquatable<T>接口

using System;
using System.Collections.Generic;

public class CustomKey : IEquatable<CustomKey>
{
    public string KeyPart1 { get; set; }
    public int KeyPart2 { get; set; }

    public bool Equals(CustomKey other)
    {
        if (other == null) return false;
        return this.KeyPart1 == other.KeyPart1 && this.KeyPart2 == other.KeyPart2;
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as CustomKey);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + (KeyPart1 != null ? KeyPart1.GetHashCode() : 0);
            hash = hash * 23 + KeyPart2.GetHashCode();
            return hash;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var customDict = new Dictionary<CustomKey, string>();

        var key1 = new CustomKey { KeyPart1 = "A", KeyPart2 = 1 };
        var key2 = new CustomKey { KeyPart1 = "B", KeyPart2 = 2 };

        customDict[key1] = "Value1";
        customDict[key2] = "Value2";

        Console.WriteLine(customDict[key1]); // Output: Value1
        Console.WriteLine(customDict[key2]); // Output: Value2
    }
}

在这个示例中,我们创建了一个名为CustomKey的自定义类,它包含两个属性:KeyPart1(字符串类型)和KeyPart2(整数类型)。我们实现了IEquatable<CustomKey>接口的Equals方法来比较两个CustomKey对象是否相等,同时重写了GetHashCode方法以确保字典可以正确地存储和检索键值对。

然后,在Main方法中,我们创建了一个Dictionary<CustomKey, string>实例,并向其添加了两个键值对。最后,我们通过键从字典中检索值并将其输出到控制台。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业