字典类:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;namespace Dict
{
public class ClassDict
{
private Hashtable words = new Hashtable();
public ClassDict()
{
words.Add("lock", "锁");
words.Add("name", "名字");
words.Add("engine", "发动机");
words.Add("carframe", "车架");
words.Add("file", "文件");
words.Add("folder", "文件夹");
} public string this[string sEnglish]
{
get
{
foreach(DictionaryEntry dKey in words)
{
if (dKey.Key.ToString() == sEnglish.ToLower())
{
return dKey.Value.ToString();
}
}
return "对不起,没找到对应汉字翻译!";
}
} public string this[object oChinese]
{
get
{
foreach (DictionaryEntry dKey in words)
{
if (dKey.Value.ToString() == oChinese.ToString())
{
return dKey.Key.ToString();
}
}
return "对不起,没找到对应英文翻译!";
}
}
}
}查中英文翻译:
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text.Trim())==false)
{
ClassDict classDict1 = new ClassDict();
char c1 = textBox1.Text.Trim()[0];
if ((int)c1 >= 0x4e00 && (int)c1 <= 0x9fa5)
{
//如果是汉字,就查英文
object o1 = textBox1.Text.Trim();
textBox2.Text = classDict1[o1];
}
else
{
//如果是英文,就查汉字
textBox2.Text = classDict1[textBox1.Text];
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;namespace Dict
{
public class ClassDict
{
private Hashtable words = new Hashtable();
public ClassDict()
{
words.Add("lock", "锁");
words.Add("name", "名字");
words.Add("engine", "发动机");
words.Add("carframe", "车架");
words.Add("file", "文件");
words.Add("folder", "文件夹");
} public string this[string sEnglish]
{
get
{
foreach(DictionaryEntry dKey in words)
{
if (dKey.Key.ToString() == sEnglish.ToLower())
{
return dKey.Value.ToString();
}
}
return "对不起,没找到对应汉字翻译!";
}
} public string this[object oChinese]
{
get
{
foreach (DictionaryEntry dKey in words)
{
if (dKey.Value.ToString() == oChinese.ToString())
{
return dKey.Key.ToString();
}
}
return "对不起,没找到对应英文翻译!";
}
}
}
}查中英文翻译:
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text.Trim())==false)
{
ClassDict classDict1 = new ClassDict();
char c1 = textBox1.Text.Trim()[0];
if ((int)c1 >= 0x4e00 && (int)c1 <= 0x9fa5)
{
//如果是汉字,就查英文
object o1 = textBox1.Text.Trim();
textBox2.Text = classDict1[o1];
}
else
{
//如果是英文,就查汉字
textBox2.Text = classDict1[textBox1.Text];
}
}
}
数据量不大Dictionary、SortedDictionary、SortedList在搜索上都差不多
如果数据量非常大,应该使用SortedDictionary
words.Add("hello world", "欢迎来到CSDN!哈哈");
谢谢。改成这样了 public class ClassDict
{
private SortedDictionary<string,string> words = new SortedDictionary<string,string>();
public ClassDict()
{
words.Add("lock", "锁");
words.Add("china", "中国");
} public string this[string sEnglish]
{
get
{
foreach(KeyValuePair<string,string> word in words)
{
if(word.Key ==sEnglish.ToLower())
{
return word.Value;
}
}
return "对不起,没找到对应汉字翻译!";
}
} public string this[object oChinese]
{
get
{
foreach (KeyValuePair<string, string> word in words)
{
if (word.Value == oChinese.ToString())
{
return word.Key;
}
}
return "对不起,没找到对应英文翻译!";
}
}
}