C#中的反射:获取类直接实现的接口并排除继承的上级接口
在C#中,如果你有一个类,并且你想获得它直接实现的接口列表,而排除掉接口继承的上级接口,你可以通过反射来实现。下面是一个示例代码,展示了如何获取类的直接实现接口并排除继承的上级接口:
C# 全选
using System;
using System.Linq;
using System.Collections.Generic;
public interface IBase { }
public interface IDerived : IBase { }
public interface IOther { }
public class MyClass : IDerived, IOther { }
public class Program
{
public static void Main()
{
var directInterfaces = GetDirectlyImplementedInterfaces(typeof(MyClass));
foreach (var iface in directInterfaces)
{
Console.WriteLine(iface.Name);
}
}
public static List<Type> GetDirectlyImplementedInterfaces(Type type)
{
// Get all interfaces implemented by the class
var allInterfaces = type.GetInterfaces();
// Create a set of all inherited interfaces
var inheritedInterfaces = new HashSet<Type>(allInterfaces.SelectMany(i => i.GetInterfaces()));
// Direct interfaces are those that are in allInterfaces but not in inheritedInterfaces
var directInterfaces = allInterfaces.Where(i => !inheritedInterfaces.Contains(i)).ToList();
return directInterfaces;
}
}
在这段代码中,GetDirectlyImplementedInterfaces方法做了以下几件事:
1. 获取类实现的所有接口:var allInterfaces = type.GetInterfaces();
2. 获取所有接口的上级接口,并放入一个集合中:var inheritedInterfaces = new HashSet<Type>(allInterfaces.SelectMany(i => i.GetInterfaces()));
3. 找出直接实现的接口,即那些在所有接口集合中但不在上级接口集合中的接口:var directInterfaces = allInterfaces.Where(i => !inheritedInterfaces.Contains(i)).ToList();
运行这段代码,你会得到MyClass直接实现的接口,而不会包含接口继承链中的上级接口。对于MyClass这个例子,输出将会是:
Markup 全选
IDerived
IOther
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 张国生