【发布时间】:2014-11-22 17:28:29
【问题描述】:
假设我在 1 个类中有一个字典函数:
public static class Class1
{
public static void StatDict(int EventNumber, string EventCode)
{
Dictionary<int, string> Dict1 = new Dictionary<int, sting>();
Dictionary.Add(EventNumber, EventCode);
}
}
输入示例:EventNumber = '4', EventCode = '4TUI'// 这是从另一个类 Class2 提供的
我想比较说,Int i = 4,在类 2 中或字典的键 4 的函数中,以便我可以提取键 4 的值。(即“4TUI”)。
public static class Class2
{
public void CompareIntToDictionary()
{
Int Compare= 4;
if (Compare == Dictionary(value);????????????????????? // *This part i need help with*
{
Do something!!!
}
}
}
谁能告诉我如何引用存在于 1 个类中的字典以提取与键关联的值,如果它与我在其他地方(即另一个类)定义的整数匹配?任何帮助将不胜感激,谢谢。
编辑:感谢这个,似乎它确实可以解决问题,除了以下代码确实返回 false,即使我知道密钥在那里,它也会跳过这个(因此为 false):
int Compare = 4;
if (Class1.Dict1.ContainsKey(Compare))
{
var eventCodecheck = Class1.Dict1[Compare];
Debug.WriteLine("eventcode = " + eventCodecheck);
// Do something!!!
}
但现在我面临的问题是我需要重写 GetHashCode 和 Equals 以便使用字典比较来自 2 个不同对象的键。
感谢有用的答案,这是我使用的代码,但我不太确定如何覆盖 GetHascode 和 Equals:
public static class Class1
{
public static Dictionary<int, string> Dict1 { get; set; }
public static void StatDict(int EventNumber, string EventCode)
{
Dict1 = new Dictionary<int, string>();
Dict1.Add(EventNumber, EventCode);
Debug.WriteLine("EventNumber = " + EventNumber + " EventCode = " + EventCode);
}
}
public static class Class2
{
public static void CompareIntToDictionary()
{
int Compare = 4;
if (Class1.Dict1.ContainsKey(Compare))
{
var eventCodecheck = Class1.Dict1[Compare];
Debug.WriteLine("eventcode = " + eventCodecheck);
// Do something!!!
}
}
}
我只是在学习这些东西。
【问题讨论】:
-
那么你的问题是什么?你的
CompareIntToDictionary方法不起作用吗? -
基本上,是的,它跳过了这个检查,即使我知道有一个键 '4' 和一个关联的值。所以,它看起来像 int compare = 4;与 Dict1 中 4 的键不同。似乎并非所有 Int 的创建都是一样的,因此哈希码....
-
int将其值作为哈希码返回,因此您不需要覆盖GetHashCode方法(实际上您不能为int执行此操作)。您确定先调用StatDict方法,然后再调用CompareIntToDictionary?此外,每次调用StatDict时,它都会创建一个新的空字典。您需要将Dict1 = new Dictionary<int, string>();移动到另一个方法并在其他方法之前调用它一次,以确保字典只创建一次。
标签: c# class object dictionary