2011-12-18 53 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 
} 
相关问题