获取类实现的接口

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(使用前将#替换为@)

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

  • WPF MVVM将DataTable绑定到DataGrid不显示数据

    我有一个简单的控件 其中包含一个 DataGrid 其中 ItemsSource 绑定到 DataTable 当我填充 DataTable 时 我可以看到 DataGrid 中添加了行 但没有显示任何数据 我没有为此 DataGrid 使用
  • Reflection.Emit 中的短格式操作码错误

    我正在制作一种与以下非常相似的小语言hlsl但仅支持像素着色器 该语言使用reflection emit构建实现相同功能的 NET 程序集 我目前正在测试分支指令的实现if在我的一个单元测试中 一个大的if与内if elses 失败并显示以
  • 将 try_emplace 与 shared_ptr 一起使用

    所以我有一个std unordered map
  • 尝试将元素推入向量

    在头文件 我没有编写 中 已经定义了一个结构体 如下所示 struct MemoryMessage public boost counted base public FastAlloc explicit MemoryMessage Memo
  • 在 C 程序中追踪数组越界访问/写入的推荐方法

    考虑用 C 语言编写一些不太明显的算法的实现 例如 让它成为递归快速排序 我在 K N King 的 C 编程 现代方法 第二版 书中找到了它 可以从here http knking com books c2 programs qsort
  • 使用 C 创建立体声正弦波

    我正在尝试用 C 创建立体声正弦 WAV 并且可能有不同的 可能是空白的 左声道和右声道 使用此函数为每个通道生成一个音调 int16 t create tone float frequency float amplitude float
  • c++11 中的 std::thread 问题

    我在尝试从标准模板库编译具有多线程的程序时遇到一些麻烦 当我尝试编译以下程序时 它返回一个晦涩的错误 include
  • 从空白启动时 VSTO 功能区不显示解决方案

    如果我从 文件 新建项目 菜单创建一个新的 Excel 2013 和 2016 VSTO 加载项 项目 然后单击 项目 添加新项目 gt 功能区 可视化设计器 则一切正常 我启动了应用程序 我的功能区显示在 Excel 中 但是 如果我首先
  • 我应该使用函数还是无状态函子?

    这两段代码做同样的事情 如您所见 它将用于排序函数 哪个更好 我通常写后一种 但我看到一些程序员像以前那样做 struct val lessthan binary function
  • 平衡两轮机器人而不使其向前/向后漂移

    我正在尝试设计一个控制器来平衡 2 轮机器人 约 13 公斤 并使其能够抵抗外力 例如 如果有人踢它 它不应该掉落 也不应该无限期地向前 向后漂移 我对大多数控制技术 LQR 滑模控制 PID 等 都很有经验 但我在网上看到大多数人使用 L
  • Xamarin 无法从异步获取实例

    我编写了一个通过蓝牙连接到 ESP32 的 Xamarin Forms 应用程序 现在我想从 MainPage xaml 页面的 CustomControl JoystickControl 获取值 我已经这样尝试过了 MainPage xa
  • Parallel.For 和 Break() 误解?

    我正在研究 For 循环中的并行性中断 看完之后this http tipsandtricks runicsoft com CSharp ParallelClass html and this http reedcopsey com 201
  • 允许 .NET WebApi 忽略 DOCTYPE 声明

    我正在尝试通过 WebApi 方法将 XML 反序列化为对象 我有以下课程 XmlRoot IsNullable false public class MyObject XmlElement Name public string Name
  • 选择要重写哪个基类的方法

    鉴于以下情况 class Observer public virtual void Observe Parameter p 0 template
  • 将参数从 Web 表单传递到 Crystal 报表

    我有一份报告 我想将其显示在网络表单上 没有参数的报告运行良好 带参数的报告让我很头疼 这是我在 BindReport 方法中编写的代码 该代码在表单的页面加载事件上调用 ReportDocument rpt new ReportDocum
  • Yield Return == IEnumerable 和 IEnumerator 吗?

    Is yield return实施的捷径IEnumerable and IEnumerator 是的 您可以在我的书 C in Depth 的第 6 章中找到更多相关信息 幸好第六章是免费提供 http www manning source
  • 更新插入 MongoDB 时如何防止出现“_t”字段?

    我有一个应用程序 它使用 MongoDB 的 C 驱动程序将 Upsert 插入 MongoDB 数据库 当我打电话给Update函数 我无法指定我要更新的类型 然后 t字段插入元素的类型 这是我用来更新插入的代码 collection U
  • 使用 LINQ to SQL 的 .NET 架构的最佳设计实践(DAL 必要吗?我们真的可以使用 POCO吗?要采用的设计模式吗?)

    我避免在 net arch n 层架构上编写看起来像是另一个线程的内容 但请耐心等待 希望我和其他人一样 在选择用于企业应用程序的架构时 考虑到当今的趋势和新兴技术 仍然没有 100 满意或不清楚应采取的最佳方法 我想我正在寻求大众社区对方
  • jquery ajax“发布”调用

    我是 jQuery 和 Ajax 的新手 并且在 发布 方面遇到问题 我正在使用 jQuery Ajax post 调用将数据保存到数据库 当我尝试保存数据时 它将 null 传递给我的 C 方法 jQuery 看起来像这样 functio
  • C++20 范围太多 |运营商?

    我在这段代码中使用 g 10 2 有谁知道为什么我最后收到编译器错误std views reverse on results3 include

随机推荐