• 对于初学者学习HashTable 不该忽视的一点


        通常我们学习如何使用HashTable的时候我们经常会看到这样一段代码
    using system; 
    using system.collections; //使用hashtable时,必须引入这个命名空间 
    class hashtable 
    {
        
    public static void main()
        
    {
            hashtable ht 
    = new hashtable(); //创建一个hashtable实例 
            ht.add("e""e");//添加key/value键值对 
            ht.add("a""a");
            ht.add(
    "c""c");
            ht.add(
    "b""b");
            
    string s = (string)ht["a"];
            
    if (ht.contains("e")) //判断哈希表是否包含特定键,其返回值为true或false 
                console.writeline("the e key:exist");
            ht.remove(
    "c");//移除一个key/value键值对 
            console.writeline(ht["a"]);//此处输出a 
            ht.clear();//移除所有元素 
            console.writeline(ht["a"]); //此处将不会有任何输出 
        }
     
    }
     

         但是我们察看MSDN 可以看到 hashtable的Add方法的参数是object,所以无论是Key,还是Value 都可以使用自定义的类(class)或(struct) 实体,将object 装入 hashtable ,这样使用起来就更方便了。可以参考如下代码

    using system; 
    using system.collections; //使用hashtable时,必须引入这个命名空间 
    class hashtable 
    {
        
    public static void main()
        
    {
            Hashtable ht 
    = new Hashtable();
            ht.Add(
    "1"new singer(1"周杰""male"));
            ht.Add(
    "2"new singer(2"蔡依""female"));
            singer s 
    =(singer)ht["1"];
            Console.WriteLine(s.Name);
        }
     
    }
     

    public class singer
    {
        
    public singer(int ID, string Name, string Type)   //构造函数
        
    {
            _id
    =ID;
            _name
    =Name;
            _type
    =Type;
        }


        
    private int _id;
        
    private string _name;
        
    private string _type;

        
    public int ID
        
    {
            
    get return _id; }
            
    set { _id = value; }
        }

        
    public string Name
        
    {
            
    get return _name; }
            
    set { _name = value; }
        }

        
    public string Type
        
    {
            
    get return _type; }
            
    set { _type = value; }
        }

    }

        这个虽然简单,但对于一些初学者在学习C#中还是很有帮助的。
  • 相关阅读:
    导入动态页面的两种方法
    JSTL之c:set
    CentOS更新源
    MVC轻量web应用
    Linux设备驱动开发流程(转)
    g++: internal compiler error: Killed (program cc1plus)Please submit a full bug report,内存不足问题解决
    .PHONY的作用
    CMake(转)
    关于a+++++b含义的问题
    返回值为函数指针的函数(转)
  • 原文地址:https://www.cnblogs.com/eoiioe/p/1140592.html
Copyright © 2020-2023  润新知