c# - 确定最接近类的子接口(interface)

标签 c# algorithm reflection inheritance interface

假设我有一个接口(interface)继承树:

IParent > IChild > IGrandChild

我会怎样:

  1. 找到一个实现 IParent 的类
  2. 确定也是 IParent 的子类的最近的祖先。

例如:

var myClass = FindImplementor<IParent>();
var myInterface = ClosestAncestor<IParent, myclass>();

我不打算创建与上述签名匹配的函数。那只是为了澄清。

IParent 的后代以及实现类都在一个动态加载的程序集中。我不确定这是否会产生影响。

最佳答案

您可以使用 as 关键字并检查是否为空。

例子:

var someObject = GetMeSomething();  //returns some IParent/IChild/IGrandChild

if ((someObject as IParent) != null)
    if ((someObject as IChild) != null)
    {
        if ((someObject as IGrandChild) != null)
        {
            //you have an IGrandChild
        }
        else
        {
            //you have an IChild
        }
    }
    else
    {
        //you have an IParent
    }
}
//you have something other than your interface hierarchy

实际上,我并不是很喜欢这个想法,但它就是我想到的。试图识别链式店存在许多问题。我想到了多个实现链。

关于c# - 确定最接近类的子接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1723228/

相关文章:

c# - 使用 lambda 重新排列 List<T>

java - 在 Java 中测试素数的最快方法是什么?

c++ - 为什么我们将 greater<string>() 传递给排序算法?

algorithm - BigOh 符号 O(log n) 何时出现?

c# - 如何设置局部变量memberExpression值

c# - 如何动态评估 C# 表达式?

c# - 在没有安装数据库程序的情况下使用C#读取数据库文件?

c# - 在 C# .NET Core 的断言有效负载中使用自定义数据为第 3 方应用程序创建 SAML 断言

c# - 接口(interface)继承接口(interface)

c# - 为什么 Reflection.Assembly LoadFile 不加载所有 DLL?