在foreach
语句的帮助下,我正在WinForms Form中的一些controls
内部进行搜索。我正在比较我通过"is"-引用(a is DataGridView
)找到的对象。其中"a"是控件集合中的对象。到目前为止,这很好,因为我表单上被比较的对象彼此之间都有足够的不同。
在我创建的一个新表单中,我使用了一个名为my_datagridview
的DataGridView
的派生版本。因此,当通过"is"-引用将my_datagridview
与DataGridView
进行比较时,不会引发异常,这是"错误的",因为我想分别处理这两者。
有没有办法正确地比较my_datagridview
和DataGridView
?
有没有一种方法可以正确地比较my_dataridview和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
}
当然,您也可以使用GetType()
进行精确匹配。重要的问题是,对于从DataGridView
甚至从MyDataGridView
派生的任何其他类,您希望发生什么。
是。首先从最具体的类别开始。因此:
if (a is my_datagridview)
{
//....
}
else if (a is DataGridView)
{
// ....
}
请参阅此处的MDSN。
首先我喜欢更好的
所以
var dg = a as DataGrindView
var mygd = a as MyDataGridView
if(mygd != null) {...}
else
{
if(dg != null) {...}
}
上行总是成功,下行总是失败
因此,当您将my_dataridview升级到datagridview时,它总是会成功的
这样做将导致InvalidCastException,因为向下转换失败!
DataGridView dgv = new DataGridView();
myDataGrivView m_dgv = (myDataGridView)dgv;
为了避免抛出上述异常,您可以使用作为运算符!
如果向下转换失败,它将返回null,而不是抛出异常!
DataGridView dgv = new DataGridView();
myDataGrivView m_dgv =dgv as myDataGridView;
if(m_dgv==null)
{
//its a datagridview
}
else
{
//its a mydatagridview
}
首先比较派生程度较高的版本并执行其操作,然后比较派生程度较低的类型(假设操作互斥)
或者,将两个比较放在一个条件语句中:
if ((a is my_datagridview) && (!a is DataGridView))
{
// This will only match your derived version and not the Framework version
}
// The else is needed if you need to do something else for the framework version.
else if (a is DataGridView)
{
// This will only match the framework DataGridView because you've already handled
// your derived version.
}
根据我们上面的评论,我认为没有必要找到控件。例如,如果您在表单上有一个按钮,并且通过单击grid1应该发生了一些事情,那么您可以使用该按钮的点击事件处理程序:
private void ClickButtonOne(object sender, EventArgs e)
{
// Do something with datagridview here
}