给定一个Object,我如何以编程方式告诉它支持哪些接口?

时间:2008-12-27 22:55:42

标签: c# .net reflection interface

鉴于此:

Interface IBase {string X {get;set;}}
Interface ISuper {string Y {get;set;}}

class Base : IBase {etc...}
class Super : Base, ISuper {etc...}

void Questionable (Base b) {
  Console.WriteLine ("The class supports the following interfaces... ")
  // The Magic Happens Here
}

我可以用“魔术”代替什么来显示对象b上支持的界面?

是的,我知道作为类Base它支持“IBase”,真正的层次结构就更复杂了。 :)

谢谢! -DF5

编辑:现在我已经看到了答案,因为没有通过Intellisense绊倒我感到愚蠢。 :)

全部谢谢! -DF5

4 个答案:

答案 0 :(得分:8)

b.GetType()。GetInterfaces()

答案 1 :(得分:8)

魔术:

foreach (Type iface in b.GetType().GetInterfaces())
    Console.WriteLine(iface.Name);

答案 2 :(得分:2)

foreach (var t in b.GetType().GetInterfaces())
{
    Console.WriteLine(t.ToString());
}

答案 3 :(得分:2)

嘿,我看到了Console.WriteLine,并认为你正在寻找一个字符串表示。无论如何这是

public string GetInterfacesAsString(Type type) { 
  return type.GetInterfaces().Select(t => t.ToString()).Aggregate(x,y => x + "," + y);
}
相关问题