获取类实现的接口

2024-04-24

我正在做装配分析项目,遇到了问题。

我想要实现的是一个类实现的所有接口的列表,但没有派生接口(以及派生类实现的接口)。

这是一个例子来说明(来自 LinqPad,.Dump()是打印到结果窗口):

void Main()
{
    typeof(A).GetInterfaces().Dump(); //typeof(IT), typeof(IT<Int32>) 
    typeof(B).GetInterfaces().Dump(); //typeof(IT<Int32>) 
    typeof(C).GetInterfaces().Dump(); //typeof(IT), typeof(IT<Int32>) 
}

class C : A {}

class A : IT {}

class B : IT<int> {}

public interface IT : IT <int> {}

public interface IT<T> {}

我想得到的是

    typeof(A).GetInterfaces().Dump();  //typeof(IT)
    typeof(B).GetInterfaces().Dump();  //typeof(IT<Int32>) 
    typeof(C).GetInterfaces().Dump();  //

我找到了这个帖子Type.GetInterfaces() 仅适用于声明的接口 https://stackoverflow.com/questions/9793242/type-getinterfaces-for-declared-interfaces-only有答案

Type type = typeof(E);
var interfaces = type.GetInterfaces()
    .Where(i => type.GetInterfaceMap(i).TargetMethods.Any(m => m.DeclaringType == type))
    .ToList();

但我正在寻找是否有一种替代方法可以迭代方法。

有什么办法可以实现这一点吗?


我尝试将我的答案写得尽可能自我记录。变量名称也可以解释它们在做什么。所以我会让代码来说话:)

public static class InterfaceDumperExtension
{

    public static Type[] DumpInterface(this Type @type)
    {
        //From your question, I think that you only want to handle
        //class case so I am throwing here but you can handle accordingly
        if (@type.IsClass == false)
        {
            throw new NotSupportedException($"{@type} must be a class but it is not!");
        }

        //All of the interfaces implemented by the class
        var allInterfaces = new HashSet<Type>(@type.GetInterfaces());

        //Type one step down the hierarchy
        var baseType = @type.BaseType;

        //If it is not null, it might implement some other interfaces
        if (baseType != null)
        {
            //So let us remove all the interfaces implemented by the base class
            allInterfaces.ExceptWith(baseType.GetInterfaces());
        }

        //NOTE: allInterfaces now only includes interfaces implemented by the most derived class and
        //interfaces implemented by those(interfaces of the most derived class)

        //We want to remove interfaces that are implemented by other interfaces
        //i.e
        //public interface A : B{}
        //public interface B {}
        //public class Top : A{}→ We only want to dump interface A so interface B must be removed

        var toRemove = new HashSet<Type>();
        //Considering class A given above allInterfaces contain A and B now
        foreach (var implementedByMostDerivedClass in allInterfaces)
        {
            //For interface A this will only contain single element, namely B
            //For interface B this will an empty array
            foreach (var implementedByOtherInterfaces in implementedByMostDerivedClass.GetInterfaces())
            {
                toRemove.Add(implementedByOtherInterfaces);
            }
        }

        //Finally remove the interfaces that do not belong to the most derived class.
        allInterfaces.ExceptWith(toRemove);

        //Result
        return allInterfaces.ToArray();
    }
}

测试代码:

public interface Interface1 { }
public interface Interface2 { }
public interface Interface3 { }
public interface DerivedInterface1 : Interface1 { }
public interface DerivedInterface2 : Interface2 { }
public class Test : DerivedInterface1, DerivedInterface2, Interface3 { }

var result = typeof(Test).DumpInterface();
//Contains only DerivedInterface1, DerivedInterface2, Interface3 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取类实现的接口 的相关文章

  • FFMPEG Seeking 带来音频伪影

    我正在使用 ffmpeg 实现音频解码器 在读取音频甚至搜索已经可以工作时 我无法找到一种在搜索后清除缓冲区的方法 因此当应用程序在搜索后立即开始读取音频时 我没有任何工件 avcodec flush buffers似乎对内部缓冲区没有任何
  • 如何在我的应用程序中使用 Windows Key

    Like Windows Key E Opens a new Explorer Window And Windows Key R Displays the Run command 如何在应用程序的 KeyDown 事件中使用 Windows
  • 为什么 POSIX 允许在只读模式下超出现有文件结尾 (fseek) 进行搜索

    为什么寻找文件结尾很有用 为什么 POSIX 让我们像示例中那样在以只读方式打开的文件中进行查找 c http en cppreference com w c io fseek http en cppreference com w c io
  • 为什么禁止在 constexpr 函数中使用 goto?

    C 14 对你能做什么和不能做什么有规则constexpr功能 其中一些 没有asm 没有静态变量 看起来相当合理 但标准也不允许goto in constexpr功能 即使它允许其他控制流机制 这种区别背后的原因是什么 我以为我们已经过去
  • c 中的错误:声明隐藏了全局范围内的变量

    当我尝试编译以下代码时 我收到此错误消息 错误 声明隐藏了全局范围内的变量 无效迭代器 节点 根 我不明白我到底在哪里隐藏或隐藏了之前声明的全局变量 我怎样才能解决这个问题 typedef node typedef struct node
  • 在 ASP.Net Core 2.0 中导出到 Excel

    我曾经使用下面的代码在 ASP NET MVC 中将数据导出到 Excel Response AppendHeader content disposition attachment filename ExportedHtml xls Res
  • 使用向量的 merge_sort 在少于 9 个输入的情况下效果很好

    不知何故 我使用向量实现了合并排序 问题是 它可以在少于 9 个输入的情况下正常工作 但在有 9 个或更多输入的情况下 它会执行一些我不明白的操作 如下所示 Input 5 4 3 2 1 6 5 4 3 2 1 9 8 7 6 5 4 3
  • 使用安全函数在 C 中将字符串添加到字符串

    我想将文件名复制到字符串并附加 cpt 但我无法使用安全函数 strcat s 来做到这一点 错误 字符串不是空终止的 我确实设置了 0 如何使用安全函数修复此问题 size strlen locatie size nieuw char m
  • 初始化变量的不同方式

    在 C 中初始化变量有多种方法 int z 3 与 int 相同z 3 Is int z z 3 same as int z z 3 您可以使用 int z z 3 Or just int z 3 Or int z 3 Or int z i
  • Windows 10 中 Qt 桌面应用程序的缩放不当

    我正在为 Windows 10 编写一个简单的 Qt Widgets Gui 应用程序 我使用的是 Qt 5 6 0 beta 版本 我遇到的问题是它根本无法缩放到我的 Surfacebook 的屏幕上 这有点难以判断 因为 SO 缩放了图
  • 更改窗口的内容 (WPF)

    我创建了一个简单的 WPF 应用程序 它有两个 Windows 用户在第一个窗口中填写一些信息 然后单击 确定 这会将他们带到第二个窗口 这工作正常 但我试图将两个窗口合并到一个窗口中 这样只是内容发生了变化 我设法找到了这个更改窗口内容时
  • .NET 选项将视频文件流式传输为网络摄像头图像

    我有兴趣开发一个应用程序 它允许我从 xml 构建视频列表 包含视频标题 持续时间等 并将该列表作为我的网络摄像头流播放 这意味着 如果我要访问 ustream tv 或在实时通讯软件上激活我的网络摄像头 我的视频播放列表将注册为我的活动网
  • 网络参考共享类

    我用 Java 编写了一些 SOAP Web 服务 在 JBoss 5 1 上运行 其中两个共享一个类 AddressTO Web 服务在我的 ApplycationServer 上正确部署 一切都很顺利 直到我尝试在我的 C 客户端中使用
  • AccessViolationException 未处理

    我正在尝试使用史蒂夫 桑德森的博客文章 http blog stevensanderson com 2010 01 28 editing a variable length list aspnet mvc 2 style 为了在我的 ASP
  • EPPlus Excel 更改单元格颜色

    我正在尝试将给定单元格的颜色设置为另一个单元格的颜色 该单元格已在模板中着色 但worksheet Cells row col Style Fill BackgroundColor似乎没有get财产 是否可以做到这一点 或者我是否必须在互联
  • 如何构建印度尼西亚电话号码正则表达式

    这些是一些印度尼西亚的电话号码 08xxxxxxxxx 至少包含 11 个字符长度 08xxxxxxxxxxx 始终以 08 开头 我发现这个很有用 Regex regex new Regex 08 0 9 0 9 0 9 0 9 0 9
  • 如何在内存中存储分子?

    我想将分子存储在内存中 这些可以是简单的分子 Methane CH4 C H bond length 108 7 pm H H angle 109 degrees But also more complex molecules like p
  • C++ 成员函数中的“if (!this)”有多糟糕?

    如果我遇到旧代码if this return 在应用程序中 这种风险有多严重 它是一个危险的定时炸弹 需要立即在应用程序范围内进行搜索和销毁工作 还是更像是一种可以悄悄留在原处的代码气味 我不打算writing当然 执行此操作的代码 相反
  • 如何将字符串“07:35”(HH:MM) 转换为 TimeSpan

    我想知道是否有办法将 24 小时时间格式的字符串转换为 TimeSpan 现在我有一种 旧时尚风格 string stringTime 07 35 string values stringTime Split TimeSpan ts new
  • 将 viewbag 从操作控制器传递到部分视图

    我有一个带有部分视图的 mvc 视图 控制器中有一个 ActionResult 方法 它将返回 PartialView 因此 我需要将 ViewBag 数据从 ActionResult 方法传递到 Partial View 这是我的控制器

随机推荐