简体   繁体   English

如何确定类型是否为抽象类的基类

[英]How to determine if type is a base class of an abstract class

To check if my type was the interface type I was using the following method 要检查我的类型是否是接口类型,我正在使用以下方法

dllFileNames = Directory.GetFiles(path, "*.dll");

ICollection<Assembly> assemblies = new List<Assembly>(dllFileNames.Length);
foreach (string dllFile in dllFileNames)
{
    AssemblyName an = AssemblyName.GetAssemblyName(dllFile);
    Assembly assembly = Assembly.Load(an);
    assemblies.Add(assembly);
}

Type pluginType = typeof(T);
foreach (Assembly assembly in assemblies)
{
    if (assembly != null)
    {
        try
        {
            Type[] types = assembly.GetTypes();

            foreach (Type type in types)
            {
                if (type.IsInterface || type.IsAbstract)
                {
                    continue;
                }
                else
                {
                    if (type.GetInterface(pluginType.FullName) != null && typeof(IBase).IsAssignableFrom(type))
                    {
                        pluginTypes.Add(type);
                    }
                }
            }
        }
        catch (Exception ex) { }
    }
}

However IsAssignableFrom is false now that I changed IBase to an abstract class. 但是,由于我将IBase更改为抽象类,因此IsAssignableFrom为false。

How do I do the same thing but for a base type of an abstract class? 除了抽象类的基本类型,我该如何做同样的事情?

EDIT: Yes my class inherits from the abstract class for sure 编辑:是的,我的课程肯定是从抽象类继承的

public class MyType : IBase{  ...   }

where 哪里

IBase is now 现在是iBase

public abstract class IBase{   ...   }

and before it used to be 在以前

public interface IBase{ ...  }

EDIT2 : unfortunately I could not recreate the issue with the following code, (both results are true) EDIT2 :不幸的是,我无法使用以下代码来重新创建问题,(两个结果均为真)

    public abstract class IBlah
    {
        string test { get; set; }
    }

    public class implementation1 : IBlah
    {
    }

    public interface IBlech
    {
        string test { get; set; }
    }

    public class implementation2 : IBlech
    {
        public string test
        {
            get
            {
                throw new NotImplementedException();
            }

            set
            {
                throw new NotImplementedException();
            }
        }
    }


    static void Main(string[] args)
    {

        try
        {
            bool result1 = (typeof(IBlah).IsAssignableFrom(typeof(implementation1)));
            bool result2 = (typeof(IBlech).IsAssignableFrom(typeof(implementation2)));
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Console.ReadKey();
        }

    }

Use type.IsSubClassOf(typeof(IBase)) 使用type.IsSubClassOf(typeof(IBase))

Documentation of IsSubClassOf on MSDN . MSDN上IsSubClassOf的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM