编辑以复制StripItem不起作用

时间:2013-01-20 00:16:42

标签: c# optimization

这是设置动态编辑复制 mnuStripItem的正确代码吗?

此代码用于复制用户突出显示的任何内容,并且输出正确。

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form f = Form.ActiveForm;

        // Find the control that has focus
        Control focusedControl = f.ActiveControl;

        // See if focusedControl is of a type that can select text/data
        if (focusedControl is TextBox)
        {
            TextBox tb = focusedControl as TextBox;
            Clipboard.SetDataObject(tb.SelectedText);
        }
        else if (focusedControl is DataGridView)
        {
            DataGridView dgv = focusedControl  as DataGridView;
            Clipboard.SetDataObject(dgv.GetClipboardContent());
        }
        //else if (...more?...)
        //{
        //}

    }

1 个答案:

答案 0 :(得分:0)

这是完全正确的,但通常当我必须处理大量的检查语句时,我更喜欢使用switch语句。它更容易阅读,我认为在这种情况下它也会表现更好(不需要使用“是”和“作为”语句):

Control focusedControl = f.ActiveControl;

switch (focusedControl.GetType())
{
    case typeof(TextBox):
        TextBox tb = (TextBox)focusedControl;
        Clipboard.SetDataObject(tb.SelectedText);
        break;

    // ...

    default:
        break;
}