简体   繁体   中英

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.

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

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)

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

Documentation of IsSubClassOf on MSDN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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