C# 如何在c中查找类中使用的接口数?

C# 如何在c中查找类中使用的接口数?,c#,C#,我期望在编译时和运行时类中实现的接口数量 由于我是c新手,请详细解释或发布链接。您可以这样尝试: foreach (Type tinterface in <your-object>.GetType().GetInterfaces()) { Console.WriteLine(tinterface.ToString()); } int numberOfImplementedInterfaces = typeof(Class_name_here).GetInterfaces()

我期望在编译时和运行时类中实现的接口数量

由于我是c新手,请详细解释或发布链接。

您可以这样尝试:

foreach (Type tinterface in <your-object>.GetType().GetInterfaces())
{
   Console.WriteLine(tinterface.ToString());
}
 int numberOfImplementedInterfaces = typeof(Class_name_here).GetInterfaces().Length; // Gives the count of implemented interfaces
 var Interfaces = typeof(Class_name_here).GetInterfaces(); // Gives the collection of interfaces

您可以通过反射来实现这一点。特别是GetInterfaces


您可以获得接口数-

<your-class-name> myobject = new <your-class-name>();
int count = myobject.GetType().GetInterfaces().Count();

更多信息请参考。

编译时是否需要此信息?此循环将打印类中使用的所有接口。但我需要类中使用的接口数。@abhishek是的。如果你跟随我文章中的链接,你会看到这个方法提供了一个数组。下面是一个确定数组长度的简单练习。
 int numberOfImplementedInterfaces = typeof(Class_name_here).GetInterfaces().Length; // Gives the count of implemented interfaces
 var Interfaces = typeof(Class_name_here).GetInterfaces(); // Gives the collection of interfaces
foreach (Type tinterface in typeof(MyType).GetInterfaces())
{
    Console.WriteLine(tinterface.ToString());
}
<your-class-name> myobject = new <your-class-name>();
int count = myobject.GetType().GetInterfaces().Count();