键值的转换

C# 枚举与哈希表应用
本文介绍了一种使用 C# 进行枚举类型与哈希表结合的应用案例,通过定义枚举 Bar 和创建哈希表来实现数据的映射,并演示了如何加载、保存及打印这些映射关系。

using System;

using System.Collections;

 

namespace demo1

{

    class Foo

    {

        enum Bar{   前= 1, 后, 左, 右 };

        Hashtable ht;

        Hashtable newht;

        // 初始化码表对应关系

        public void Load()

        {

            Hashtable rt = new Hashtable();

            rt[4] = "right";

            rt[3] = "back";

            rt[2] = "left";

            rt[1] = "foward";

            ht = rt;

        }

        // 转换成新的对应关系

        public void Save()

        {

            newht = new Hashtable();

            foreach(DictionaryEntry de in ht)

            {

                Console.WriteLine(string.Format("key: {0}  value: {1}", de.Key, de.Value));

                if(Enum.IsDefined(typeof(Bar), de.Key)){

                    Bar bar = (Bar)de.Key;

                    Console.WriteLine(string.Format("枚举 -> {0}", bar.ToString()));

                    newht[bar.ToString()] = de.Value;

                }

            }

        }

        public void Print()

        {

            // 删除一对

            Bar bar = Bar.后;

            //newht[bar.ToString()] = "";

            newht.Remove(bar.ToString());

            Console.WriteLine("\n新对应关系");

            foreach(DictionaryEntry de in newht)

            {

                Console.WriteLine(string.Format("key: {0} value: {1}", de.Key, de.Value));

            }

        }

    }

    class MainClass

    {

        public static void Main (string[] args)

        {

            Foo foo = new Foo();

            foo.Load();

            foo.Save();

            foo.Print();

        }

    }

}

转载于:https://www.cnblogs.com/Akiller/p/3183855.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值