我如何遍历我的类对象添加哈希表对象

时间:2017-12-05 07:31:31

标签: c#

// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}

我收到了这个错误:

  

HashTableDemo.exe中出现未处理的“System.InvalidCastException”类型异常

3 个答案:

答案 0 :(得分:1)

尝试,因为hash tbale中的数据存储不是Friend对象的类型,如果您不知道类型而不是使用将解决错误的var

  foreach (var  item in myhash)
        {
           string key = de.Key.ToString();
           Friend val  = (Friend) item.Value;
           Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
        }

或者你可以这样做

foreach(DictionaryEntry de in myHashtable)
{
      string key = de.Key.ToString();
   Friend val  = (Friend) de.Value;
   Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, val.Name, val.Age );
}

宣读:Hashtable Class

答案 1 :(得分:0)

Hashtable的迭代器(枚举器)返回DictionaryEntry类型的对象。因此,在foreach循环中,每个项目都有两个属性:KeyValue,两者都属于object类型。您可以将每个项目的KeyValue属性单独投射到所需类型。例如:

foreach (DictionaryEntry item in myhash)
{
    // Cast item.Key to string
    string key = (string)item.Key;

    // And cast item.Value to Friend
    Friend friend = (Friend)item.Value;

    Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, friend.Name, friend.Age);
}

答案 2 :(得分:0)

使用强类型字典(需要using System.Collections.Generic):

using System.Collections.Generic;

public class Program
{
    class Friend
    {
        public string Name {get;set;}    
        public int Age {get;set;}

        public Friend(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    public static void Main()
    {
        // this is my class object
        Friend f1 = new Friend("Nazir", 24);
        Friend f2 = new Friend("Hamza", 24);
        Friend f3 = new Friend("Abdullah", 23);
        var myDict = new Dictionary<string, Friend>();
        // add this object in hashtable object
        myDict["13b-049-bs"] = f1;
        myDict["13b-034-bs"] = f1;
        myDict["13b-038-bs"] = f1;
        foreach (KeyValuePair<string, Friend> item in myDict)
        {
            Console.WriteLine("Key {0}\tName {1}\tAge {2}", item.Key, item.Value.Name, item.Value.Age);
        }
    }
}

强类型的优势在于你永远不会在{d}中放置Enemy(或其他类型的内容 - 除非它来自Friend