2011-03-01 79 views
5

鑑於這種情況該對象如何檢查實現了接口

interface A {} 

class B : A {} 

A b = new B(); 

我如何檢查對象B從接口A創建?

+2

「接口A創建」是什麼意思?你可以告訴你可以使用'b'的值作爲實現'A'的參考,因爲它被分配給'A'類型的變量......請澄清你的問題。 – 2011-03-01 11:06:34

回答

10

嘗試使用is

if(b is A) 
{ 
    // do something 
} 

是你想要的嗎?

+1

是的,當然!這正是我所期待的!謝謝! – Makach 2011-03-01 11:12:14

5

你可以做這樣的測試:

var b = new B(); 

var asInterface = x as A; 
if (asInterface == null) 
{ 
    //not of the interface A! 
} 
0

我們發現它的實際使用下列內容:

IMyInterface = instance as IMyInterface; 
if (intance != null) 
{ 
//do stuff 
} 

「作爲」是快於「是」,也就是節省了數鑄件 - 如果您的實例impelments IMyInterface的,你需要無更多的演員。

+0

我不太在意速度,在語義上我認爲使用更合適的是 – Makach 2011-03-01 11:17:44

+0

@Dmitry - 你有證明測試鏈接嗎?因爲我剛剛嘗試過1000000000迭代與「是」和「爲」和「是」稍快 – Stecya 2011-03-01 11:20:21

+0

那裏你去:http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword- in-the-clr,在Is返回true之後你還要做什麼?再施放一次嗎?:) – 2011-03-01 11:30:55

相關問題