在C#中,如何查找给定对象是否具有特定的祖先?找出对象是否具有特定的类作为祖先
例如,假设我有以下类结构。
ContainerControl | +----> Form | +--> MyNormalForm | +--> MyCustomFormType | +---> MyCustomForm
如果我有这样的方法:
void MyCoolMethod (Form form)
如何找到,如果从形式或MyCustomFormType不下降?
在C#中,如何查找给定对象是否具有特定的祖先?找出对象是否具有特定的类作为祖先
例如,假设我有以下类结构。
ContainerControl | +----> Form | +--> MyNormalForm | +--> MyCustomFormType | +---> MyCustomForm
如果我有这样的方法:
void MyCoolMethod (Form form)
如何找到,如果从形式或MyCustomFormType不下降?
if (form is MyCustomFormType) {
// form is an instance of MyCustomFormType!
}
的is
操作:
bool isOk = form is MyCustomForm;
if(form is MyCustomFormType)
如果你打算将它转换为这种类型的,你应该使用操作人员和检查空。
MyCustomFormType myCustomFormType = form as MyCustomFormType;
if(myCustomFormType != null)
{
// this is the type you are looking for
}
您赢得了IMO的实际使用情况。 – 2010-06-30 15:37:53
使用is
运算符。
例如
if (form is MyCustomFormType) {
do whatever
}
void MyCoolMethod (Form form) {
if (form is MyCustomFormType)
// do your cool stuff here
}
var myCustomForm = form as MyCustomFormType;
if(myCustomForm != null)
{
// form was a MyCustomFormType instance and you can work with myCustomForm
}
避免is
,如果你要处理的形式作为MyCustomFormType。通过使用,你只需要一个演员。
由于任何数量的受访者增加了:通过is
(或as
)运营商。
但是,想要找出确切的类型是classiccode smell。尽量不要那样做。如果你想根据表单的确切类型做出决定,那就试试把这个逻辑放在虚拟方法中而不是在你的课堂外。
好点。我将它放入的方法实际上是一个扩展方法(ShowDialog2)。我需要根据其祖先显示不同的对话。 (莫代尔vs无模式) – Vaccano 2010-06-30 15:44:29
如果你还需要在if块中使用它,那么'var theForm = form as MyCustomFormType;如果(theForm!= null){}'也适用。 – chakrit 2010-06-30 15:35:42
我感到跛脚......我知道这一点。这将是一个难忘的日子..... – Vaccano 2010-06-30 15:48:20