2012-07-25 74 views
2

我在WinForms表单中搜索一些controls,在foreach声明的帮助下。 我正在比较通过“is”参考(a is DataGridView)找到的对象。 “a”是控制集体中的对象。 到目前为止效果很好,因为我表格上的比较对象都是完全不同的。“is”-reference或gettype()

在我创建的新表单中,我使用了名为my_datagridviewDataGridView的派生版本。所以当一个my_datagridview通过“is”引用与DataGridView进行比较时,不会引发异常,这是“错误的”,因为我想单独处理这两个。

有没有办法正确比较my_datagridviewDataGridView

+0

为什么你通过控制需要循环时,你已经知道哪个网格应该以什么方式?只是好奇。 – danish 2012-07-25 15:53:47

+0

@danish:因为它为我节省了很多代码。所有的'DataGridViews'都包含在多个'GroupBoxes'(至少2层)中,我有8个('DataGridViews')。 这样更加整洁。 – Rufus 2012-07-25 16:11:41

+0

我仍然无法理解需要找到控制。如果屏幕上的用户操作X应该导致网格Z中的操作Y,为什么不捕获操作X并在网格上执行操作? – danish 2012-07-25 16:14:30

回答

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 
} 

或者你使用GetType()匹配,当然确切。重要的问题是你想要从DataGridView或甚至从MyDataGridView派生的任何其他类别发生。

+2

谢谢你保护我们的理智。 – 2012-07-25 15:53:18

+0

感谢您的快速回答。 我没有任何其他派生类,不打算包含/创建其他类。 – Rufus 2012-07-25 15:56:39

2

是的。首先从最具体的课程开始。所以:

if (a is my_datagridview) 
{ 
    //.... 
} 
else if (a is DataGridView) 
{ 
    // .... 
} 

See MDSN here

0

首先比较了多个派生版本,并执行其行动,然后比较少派生类型(假定行动是相互排斥的)

或者,把两个比较在一个条件语句:

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. 
} 
1

首先我想更好的

所以

var dg = a as DataGrindView 
var mygd = a as MyDataGridView 

if(mygd != null) {...} 
else 
{ 
    if(dg != null) {...} 
} 
1

Upcast总是成功,downcast总是失败!

因此,当你向my_datagridview上传DataGridView时,它总会成功!

这样做的低垂失败会导致一个InvalidCastException的

DataGridView dgv = new DataGridView(); 
myDataGrivView m_dgv = (myDataGridView)dgv; 

为了避免上述异常抛出,则可以使用操作!

而不是抛出异常,它会返回null如果downcast失败!

DataGridView dgv = new DataGridView(); 
myDataGrivView m_dgv =dgv as myDataGridView; 

if(m_dgv==null) 
{ 
//its a datagridview 
} 
else 
{ 
//its a mydatagridview 
} 
0

根据我们上面的评论,我没有看到需要找到控件。例如,如果你在表格上,并通过点击一个按钮的东西应该发生在GRID1,你可以在单击事件处理程序使用的按钮:

private void ClickButtonOne(object sender, EventArgs e) 
{ 
// Do something with datagridview here 
} 
+0

没有“需要”,它只是更短的这种方式。 – Rufus 2012-07-25 16:51:51

+0

较短并不总是有效。 – danish 2012-07-25 16:53:10