首页主机资讯在C#中如何自定义字典的键类型

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

时间2024-09-11 16:46:03发布访客分类主机资讯浏览620
导读:在C#中,要自定义字典的键类型,您需要创建一个自定义类并实现IEquatable<T>接口 using System; using System.Collections.Generic; public class Custom...

在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> 实例,并向其添加了两个键值对。最后,我们通过键从字典中检索值并将其输出到控制台。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 在C#中如何自定义字典的键类型
本文地址: https://pptw.com/jishu/698570.html
C#字典的键值对如何排序 C#字典的查找效率如何提高

游客 回复需填写必要信息