簡體   English   中英

如何確定類型是否為抽象類的基類

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

要檢查我的類型是否是接口類型,我正在使用以下方法

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) { }
    }
}

但是,由於我將IBase更改為抽象類,因此IsAssignableFrom為false。

除了抽象類的基本類型,我該如何做同樣的事情?

編輯:是的,我的課程肯定是從抽象類繼承的

public class MyType : IBase{  ...   }

哪里

現在是iBase

public abstract class IBase{   ...   }

在以前

public interface IBase{ ...  }

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();
        }

    }

使用type.IsSubClassOf(typeof(IBase))

MSDN上IsSubClassOf的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM