2011-12-18 55 views
3

假設我有一類像如何確定一類具有實現特定接口或不

interface ISampleInterface 
{ 
    void SampleMethod(); 
} 

class ImplementationClass : ISampleInterface 
{ 
// Explicit interface member implementation: 
void ISampleInterface.SampleMethod() 
{ 
    // Method implementation. 
} 

static void Main() 
{ 
    // Declare an interface instance. 
    ISampleInterface obj = new ImplementationClass(); 

    // Call the member. 
    obj.SampleMethod(); 
} 
} 

從主要方法我怎麼能確定ImplementationClass類寫作類似下面

代碼之前實現 ISampleInterface
SampleInterface obj = new ImplementationClass(); 
obj.SampleMethod(); 

有什麼辦法....請討論。謝謝。使用

+0

好如果你需要知道這一點,推測在執行時你有* *東西*你有一個對象,或只是類型的名稱,或者是什麼? –

+0

Erm看代碼或元數據類 –

+1

@JonSkeet也許我錯了,但我認爲OP是問如何在設計時確定它。 –

回答

4

你可以使用反射:

bool result = typeof(ISampleInterface).IsAssignableFrom(typeof(ImplementationClass)); 
3
public static bool IsImplementationOf(this Type checkMe, Type forMe) 
    { 
     foreach (Type iface in checkMe.GetInterfaces()) 
     { 
      if (iface == forMe) 
       return true; 
     } 

     return false; 
    } 

叫它:

if (obj.GetType().IsImplementationOf(typeof(SampleInterface))) 
    Console.WriteLine("obj implements SampleInterface"); 
11

is keyword是一個很好的解決方案。你可以測試一個對象是一個接口還是另一個類。你會做這樣的事情:

if (obj is ISampleInterface) 
{ 
    //Yes, obj is compatible with ISampleInterface 
} 

如果你沒有在運行時對象的實例,但Type,你可以使用IsAssignableFrom:

Type type = typeof(ISampleInterface); 
var isassignable = type.IsAssignableFrom(otherType); 
1

當您對實現類進行硬編碼時,您知道它實現了哪個接口,因此您只需查看源代碼或文檔即可知道哪些接口是交流lass工具。

如果您收到未知類型的對象,則有多種方法來檢查的接口的實現:

void Test1(object a) { 
    var x = a as IMyInterface; 
    if (x != null) { 
     // x implements IMyInterface, you can call SampleMethod 
    } 
} 

void Test2(object a) { 
    if (a is IMyInterface) { 
     // a implements IMyInterface 
     ((IMyInterface)a).SampleMethod(); 
    } 
} 
1

一種模式(由FxCop推薦)

SampleInterface i = myObject as SampleInterface; 
if (i != null) { 
    // MyObject implements SampleInterface 
} 
相關問題