2009-07-14 57 views
-1

我有一个接口和一些继承它的类。从接口类型检测类

public interface IFoo {} 
public class Bar : IFoo {} 
public class Baz : IFoo {} 

如果我得到它实现IFoo的类型,我怎么能决定是否型将是一个BarBaz(而不实际创建的对象)?

// Get all types in assembly. 
Type[]   theTypes = asm.GetTypes(); 

// See if a type implement IFoo. 
for (int i = 0; i < theTypes.Length; i++) 
{ 
    Type t = theTypes[i].GetInterface("IFoo"); 
    if (t != null) 
    { 
     // TODO: is t a Bar or a Baz? 
    } 
} 

回答

3

t既不是Bar也不Baz - 这是IFootheTypes[i]BarBaz

+0

好了,所以我用IsSubclassOf [I]测试theTypes ......是正确的比较方法?简单的'=='似乎不起作用。 – Nick 2009-07-14 21:32:05

0

我错过了什么吗?

theTypes[i]是类型。

4
if (theTypes[i] == typeof(Bar)) 
{ 
    // t is Bar 
} 
else if (theTypes[i] == typeof(Baz)) 
{ 
    // t is Baz 
} 
2

当您执行GetInerface时,您只能获取接口。你需要做的只是获得像这样实现接口的类型。

var theTypes = asm.GetTypes().Where(
            x => x.GetInterface("IFoo") != null 
            ); 

现在你可以通过它们循环并做到这一点。或使用开关。

foreach (var item in theTypes) 
    { 
    if (item == typeof(Bar)) 
     { 
     //its Bar 
     } 
    else if (item == typeof(Baz)) 
     { 
     ///its Baz 
     } 
    } 
0

强类型的解决方案,“难道型X实现接口I”,支持分析/重构是:

这么说,我真的不知道你正在试图完成。

+0

更像是“将所有实现接口I的东西放在基于类型的列表中”。原来的实现实际上构建了每一个对象,这显然是浪费内存和缓慢。我只是将类型存储,并按需构建对象。 – Nick 2009-07-14 22:09:33

+2

更快,做到这一点的方法是bool implementsInterface = typeof(IFoo).IsAssignableFrom(x); – 2009-07-14 22:42:06

1

我认为这将您的问题有所帮助:

IFoo obj = ...; 
Type someType = obj.GetType(); 
if (typeof(Bar).IsAssignableFrom(someType)) 
    ... 
if (typeof(Baz).IsAssignableFrom(someType)) 
    ...