2012-10-20 38 views
1

即时创建我的应用程序功能,将重新创建CTRL + Z的事情。我有几个textboxs和我做了一个表是这样的:有问题HashTable的编译错误(缺少强制转换?)

hashtable textChanges[obj.Name, obj.Text] = new HashTable(50);

IM extractthe值从chossen关键。即使keyDown被解雇,我也得到了钥匙。

事件即时寻找具有焦点的控制,并用自己的名字来提取最后一个值,他进入表。

这就是事件代码:

这是怎么我添加键&价值的哈希表

private void textBox_OnTextChange(object sender, EventArgs e) 
    { 
     if (sender.GetType() == typeof(TextBox)) 
     { 
      TextBox workingTextBox = (TextBox)sender; 
      textChanges.Add(workingTextBox.Name, workingTextBox.Text); 
     } 

     if (sender.GetType() == typeof(RichTextBox)) 
     { 
      RichTextBox workingRichTextBox = (RichTextBox)sender; 
      textChanges.Add(workingRichTextBox.Name, workingRichTextBox.Text); 
     } 
    } 

为什么我得到缺少强制错误?

(对不起,我的英语)

+6

你还在使用'HashTable'任何理由吗?包括'字典<,>'在内的通用集合在7年前出现,使生活更加美好... –

+0

i thgohot泛型dosnt在XP上工作。我在工作吗? – samy

+0

FYI - 两个'TextBox'和'RichTextBox'也['TextBoxBase'](http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase(V = VS.100) .aspx),它具有'Name'和'Text'等属性。 –

回答

3

您需要将其转换为字符串。如果你使用字典会更好。 Dictionary是一个泛型类型,你不需要hashtable所需的类型转换。 Hashtable stores the object type and you are required to type cast the object back to your desired type

obj.Text = textChanges[obj.Name].ToString(); 
+0

但是,这不是obj.Name返回一个字符串? – samy

+0

哈希表存储对象不是类型您更好地使用字典,http://stackoverflow.com/questions/301371/why-is-dictionary-preferred-over-hashtable – Adil

+0

喔,好,我现在就买下THX。当10mintus wair结束时,我会给你正确的答案。 – samy

2

是的,你需要类型转换。

但考虑重构你的代码。用户generic dictionary而不是哈希表:

Dictionary<string, string> textChanges = new Dictionary<string, string>(50); 

而且使用LINQ检索集中文本框:

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Control && e.KeyData == Keys.Z) 
    { 
     foreach (var textBox in Controls.OfType<TextBox>().Where(x => x.Focused)) 
      textBox.Text = textChanges[textBox.Name]; 
    } 
}