您的位置:山东十一选五开奖 > 小说 > Dictionary <(Of <(TKey, TValue>)>) Class Example

Dictionary <(Of <(TKey, TValue>)>) Class Example

2019-10-08 01:37

自从第一天接触到泛型、就对泛型产生了一种特殊的感觉、就像是一见钟情、 因此ArrayList 就被我无情地抛弃了,怎么感觉像是在写小说啊,呵呵… 言归正传

图片 1图片 2代码

      就在刚才在做一个自定义控件(具体说来就是这个控件的需要绑定一个本地的文件,而且还要显示一个缩略图、这个缩略图是根据文件的格式(即后缀名)来动态设定的,文件格式是用 枚举类型保存),由于其中的一些代码变化比较多(例如:增加了几个后缀名、如果绑定缩略图的代码死板地放在自定义控件内、那么此时增加几种文件格式时 就要重新编译该DLL),出于这样初衷 我把文件格式(枚举类型)与要绑定的缩略图 之间的对应关系 以键值对的格式来保存,然后把这种对应关系(key 用枚举、Value 用Image) 作为接口中的属性对外公开、在使用该自定义控件时再去动态设定它就OK啦。
      保存这种对应关系起初是用的Hashtable,感觉不太方便使用,查了查MSDN 看到了 Dictionary <(Of <(TKey, TValue>)>) Class,感觉不错、所以把对应关系又换成了Dictionary <(Of <(TKey, TValue>)>) 类型。

#! /usr/bin/env python 
#-*- coding:utf-8 -*-

import os, sys

class Workers:
#This is a class of workers working in the company. 
    def __init__(self, name, position, email, age, salary):
        self.name = name
        self.position = position
        self.email = email
        self.age = age
        self.salary = salary
class ITWorkers(Workers):
    OS = 'WinNT'
    def __init__(self, language, *av):
        Workers.__init__(self, *av)
        self.language=language
    def work(self, n):
        if self.position == 'web creator': 
            w = 'makes web site'
        elif self.position == 'server administrator':
            w = 'checks the trafic'
        elif self.position == 'programmer':
            w = 'writes programs'
        print '%s %s for %d, hours using %s on %s' % (self.name, w, n, self.language, self.OS)

henley = ITWorkers('PHP', 'Henley', 'web creator', 'henley@livegate.com', 32, 700)
thomas = ITWorkers('Python', 'Thomas', 'server administrator', 'thomas@livegate.com', 37, 900)
gates = ITWorkers('C', 'Gates', 'programmer', 'gates@livegate.com', 42, 1200)

henley.OS = 'Mac'
thomas.OS = 'Linux'

if __name__ == '__main__':
    henley.work(8)
    thomas.work(7)
    gates.work(10)                                                                                    

图片 3图片 4代码

 

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys.
        //
        Dictionary<string, string> openWith = 
            new Dictionary<string, string>();

        // Add some elements to the dictionary. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is 
        // already in the dictionary.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with Key = "txt" already exists.");
        }

        // The Item property is another name for the indexer, so you 
        // can omit its name when accessing elements. 
        Console.WriteLine("For key = "rtf", value = {0}.", 
            openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = "rtf", value = {0}.", 
            openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is
        // not in the dictionary.
        try
        {
            Console.WriteLine("For key = "tif", value = {0}.", 
                openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = "tif" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the dictionary, TryGetValue can be a more efficient 
        // way to retrieve values.
        string value = "";
        if (openWith.TryGetValue("tif", out value))
        {
            Console.WriteLine("For key = "tif", value = {0}.", value);
        }
        else
        {
            Console.WriteLine("Key = "tif" is not found.");
        }

        // ContainsKey can be used to test keys before inserting 
        // them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = "ht": {0}", 
                openWith["ht"]);
        }

        // When you use foreach to enumerate dictionary elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }

        // To get the values alone, use the Values property.
        Dictionary<string, string>.ValueCollection valueColl =
            openWith.Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for dictionary values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        Dictionary<string, string>.KeyCollection keyColl =
            openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("nRemove("doc")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key "doc" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe

Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe

Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht

Remove("doc")
Key "doc" is not found.
 */

Result

 

 

本文由山东十一选五开奖发布于小说,转载请注明出处:Dictionary <(Of <(TKey, TValue>)>) Class Example

关键词: