1

我在我的应用程序中创建了一个将重新创建 CTRL+Z 的功能。我有几个文本框,我做了一个这样的表格:

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

我在从选择的键中提取值时遇到问题。我在 keyDown 被触发后得到了钥匙。

如果我正在寻找具有焦点的控件,并使用他的名字来提取他进入表格的最后一个值。

这是事件代码:

 private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyData == Keys.Z)
        {
            for (int i = 0; i < this.Controls.Count; i++)
            {
                if (this.Controls[i].Focused)
                {
                    if (this.Controls[i].GetType() == typeof(TextBox))
                    {
                        TextBox obj = (TextBox)this.Controls[i];
                        obj.Text = textChanges[obj.Name]; // <--- compile error
                       //Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)   

                    }
                }
            }
        }
    }

这就是我向 HashTable 添加键和值的方式

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);
        }
    }

为什么我会错过演员表错误?

(对不起我的英语不好)

4

2 回答 2

3

您需要将其转换为字符串。如果你使用字典会更好。字典是一种通用类型,您不需要哈希表所需的类型转换。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();
于 2012-10-20T14:41:09.687 回答
2

是的,您需要类型转换。

但是考虑重构你的代码。用户通用字典而不是哈希表:

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];
    }
}
于 2012-10-20T15:02:31.867 回答