Skip to main content
 首页 » 编程设计

c#之当值作为对象给出时如何从哈希表中检索数据

2024年02月05日8dudu

你好,我想在哈希表中输入三个值,所以我输入一个值作为键,另外两个将它们转换为对象并作为值传递`

class UsingHashTable 
{ 
    public int empId; 
    public String empName { get; private set; } 
    public decimal salary { get; private set; } 
 
    public UsingHashTable(string empName, decimal salary) 
    { 
        this.empName = empName; 
        this.salary = salary; 
    } 
 
    Hashtable employeeHash = new Hashtable(); 
 
    UsingHashTable emp; 
 
    Console.WriteLine("Enter Employee ID "); 
    empId = Convert.ToInt32(Console.ReadLine()); 
 
    Console.WriteLine("Enter Employee Name "); 
    empName = Console.ReadLine(); 
 
    Console.WriteLine("Enter Salary of the employee "); 
    salary = Convert.ToDecimal(Console.ReadLine()); 
 
    emp = new  UsingHashTable(empName,salary); 
 
    employeeHash.Add(empId, emp); 
} 

现在真正的问题来了!如何从键所在的哈希表中检索值,但我需要从值中检索两个值如何??

foreach(DictionaryEntry temp in employeeHash)  
{ 
    Console.WriteLine(temp.Key + " " + temp.Value.eName + " " + temp.Value.salary); 
} 

我确实在 temp.Value.eName 和 temp.Value.salary 收到错误

请您参考如下方法:

你需要投temp.Value适合你的类型

Console.WriteLine(temp.Key + " " + ((UsingHashTable)temp.Value).eName + " " + ((UsingHashTable)temp.Value).salary); 

但我肯定会推荐使用 Dictionnary<TKey,TValue>这将避免转换的需要。

var employeeHash = new Dictionary<int,UsingHashTable> 
var emp = new  UsingHashTable(empName,salary); 
employeeHash.Add(empId, emp);  

你的循环会工作得很好

 foreach(var temp in employeeHash)  
 { 
     Console.WriteLine(temp.Key + " " + temp.Value.eName + " " + temp.Value.salary); 
 }