2010-06-30 61 views
2

在C#中,如何查找給定對象是否具有特定的祖先?找出對象是否具有特定的類作爲祖先

例如,假設我有以下類結構。

 
ContainerControl 
| 
+----> Form 
      | 
      +--> MyNormalForm 
      | 
      +--> MyCustomFormType 
        | 
        +---> MyCustomForm 

如果我有這樣的方法:

void MyCoolMethod (Form form) 

如何找到,如果從形式或MyCustomFormType不下降?

回答

8
if (form is MyCustomFormType) { 
    // form is an instance of MyCustomFormType! 
} 
+0

如果你還需要在if塊中使用它,那麼'var theForm = form as MyCustomFormType;如果(theForm!= null){}'也適用。 – chakrit 2010-06-30 15:35:42

+0

我感到跛腳......我知道這一點。這將是一個難忘的日子..... – Vaccano 2010-06-30 15:48:20

0

is操作:

bool isOk = form is MyCustomForm; 
4
if(form is MyCustomFormType) 

如果你打算將它轉換爲這種類型的,你應該使用操作人員和檢查空。

MyCustomFormType myCustomFormType = form as MyCustomFormType; 
if(myCustomFormType != null) 
{ 
    // this is the type you are looking for 
} 
+0

您贏得了IMO的實際使用情況。 – 2010-06-30 15:37:53

0

使用is運算符。

例如

if (form is MyCustomFormType) { 
    do whatever 
} 
0
void MyCoolMethod (Form form) { 
    if (form is MyCustomFormType) 
    // do your cool stuff here 
} 
0
var myCustomForm = form as MyCustomFormType; 
if(myCustomForm != null) 
{ 
    // form was a MyCustomFormType instance and you can work with myCustomForm 
} 

避免is,如果你要處理的形式作爲MyCustomFormType。通過使用,你只需要一個演員。

2

由於任何數量的受訪者增加了:通過is(或as)運營商。

但是,想要找出確切的類型是classiccode smell。儘量不要那樣做。如果你想根據表單的確切類型做出決定,那就試試把這個邏輯放在虛擬方法中而不是在你的課堂外。

+0

好點。我將它放入的方法實際上是一個擴展方法(ShowDialog2)。我需要根據其祖先顯示不同的對話。 (莫代爾vs無模式) – Vaccano 2010-06-30 15:44:29

相關問題