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开发框架网发布内容,转载请附上原文出处连接
张国生
上一篇:TS有两个对象,便利B对象的属性,如果A对象有这个属性,就把B的值更新到A对象。
下一篇:使用 .NET Core 和 Quartz.NET 实现任务调度持久化:更相信配置任务调度
评论列表

发表评论

评论内容
昵称:
关联文章

C#反射获取直接实现接口排除继承上级接口
C#获得类型Type实现接口列表,支持排除实现接口
ABP VNext框架基础知识介绍(1)--框架基础继承关系
协议处理实现
在ABP VNext框架对HttpApi模块控制器进行基封装
C#进化——C#发展史、C#1.0-10.0语法系统性梳理、C#与JAVA对比
css样式排除某个属性,或者样式名称
使用.NET 6开发TodoList应用(填坑1)——实现当前登录用户获取
YESWin Winform开发框架 Form窗体继承关系
C# 扫描识别图片文字(.NET Framework)
Blazor Webassembly多标签页实现非iframe实现
C# 利用Autofac批量接口注入依赖【学习记录】
使用.NET 6开发TodoList应用(11)——使用FluentValidation和MediatR实现接口请求验证
C#从文件夹随机获取一个文件
API接口安全设计方案
Electron调用C#库dll
.NET6一些常用组件配置及使用记录,持续更新。。。
Quartz在.NET使用
C# - 逆变具体应用场景
CEFSharp致性JS脚本获取返回数据

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码