"是"-reference或gettype()

Ruf*_*fus 2 .net c# comparison winforms

controlsforeach声明的帮助下,我在WinForms表单中搜索一些内容.我正在通过"is"-reference(a is DataGridView)比较我找到的对象."a"是控制集合中的对象.到目前为止工作正常,因为我的表单上的比较对象都是完全不同的.

在我创建的新表单中,我使用的是DataGridView被调用的派生版本my_datagridview.因此当a my_datagridview与a DataGridView通过"is" - 引用进行比较时,不会抛出任何异常,这是"错误的"因为我想单独处理这两个.

有没有办法比较my_datagridviewDataGridView正确?

Jon*_*eet 6

有没有办法正确比较my_datagridview和DataGridView?

一种选择是使用类似的东西:

if (a is MyDataGridView) // Type name changed to protect reader sanity
{
}
else if (a is DataGridView)
{
    // This will include any subclass of DataGridView *other than*
    // MyDataGridView
} 
Run Code Online (Sandbox Code Playgroud)

当然,或者你可以使用GetType()完全匹配.重要的问题是,您希望从源自甚至来自的任何其他类中发生什么.DataGridViewMyDataGridView

  • 感谢您保护我们的理智. (2认同)