gpt4 book ai didi

C# 通用字典 TryGetValue 找不到键

转载 作者:可可西里 更新时间:2023-11-01 08:43:04 25 4
gpt4 key购买 nike

我有这个简单的例子:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dictionary<MyKey, string> data = new Dictionary<MyKey, string>();
data.Add(new MyKey("1", "A"), "value 1A");
data.Add(new MyKey("2", "A"), "value 2A");
data.Add(new MyKey("1", "Z"), "value 1Z");
data.Add(new MyKey("3", "A"), "value 3A");

string myValue;
if (data.TryGetValue(new MyKey("1", "A"), out myValue))
Console.WriteLine("I have found it: {0}", myValue );

}
}

public struct MyKey
{
private string row;
private string col;

public string Row { get { return row; } set { row = value; } }
public string Column { get { return col; } set { col = value; } }

public MyKey(string r, string c)
{
row = r;
col = c;
}
}
}

这工作正常。但是,如果我以这种方式通过 MyKey 类更改 MyKey 结构:

public class MyKey

然后方法 TryGetValue 没有找到任何 key ,尽管 key 就在那里。

我确信我遗漏了一些明显的东西,但我不知道是什么。

有什么想法吗?

谢谢


** 解决方案 **

(请参阅接受的解决方案以获得更好的 GetHashCode 解析)

我已经像这样重新定义了 MyKey 类,现在一切正常:

public class MyKey
{
private string row;
private string col;

public string Row { get { return row; } set { row = value; } }
public string Column { get { return col; } set { col = value; } }

public MyKey(string r, string c)
{
row = r;
col = c;
}

public override bool Equals(object obj)
{
if (obj == null || !(obj is MyKey)) return false;

return ((MyKey)obj).Row == this.Row && ((MyKey)obj).Column == this.Column;
}

public override int GetHashCode()
{
return (this.Row + this.Column).GetHashCode();
}
}

感谢所有回答此问题的人。

最佳答案

您需要重写 MyKey 类中的 Equals()GetHashCode()

也许是这样的:

GetHashCode()

public override int GetHashCode()
{
return GetHashCodeInternal(Row.GetHashCode(),Column.GetHashCode());
}
//this function should be move so you can reuse it
private static int GetHashCodeInternal(int key1, int key2)
{
unchecked
{
//Seed
var num = 0x7e53a269;

//Key 1
num = (-1521134295 * num) + key1;
num += (num << 10);
num ^= (num >> 6);

//Key 2
num = ((-1521134295 * num) + key2);
num += (num << 10);
num ^= (num >> 6);

return num;
}
}

等于

public override bool Equals(object obj)
{
if (obj == null)
return false;
MyKey p = obj as MyKey;
if (p == null)
return false;

// Return true if the fields match:
return (Row == p.Row) && (Column == p.Column);
}

关于C# 通用字典 TryGetValue 找不到键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9976224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com