如何确定type是否是抽象类的基类

时间:2018-04-25 21:20:31

标签: c#

要检查我的类型是否是我使用以下方法的接口类型

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

然而IsAssignableFrom因为我将IBase更改为抽象类而失败。

如何对基本类型的抽象类做同样的事情?

修改 是的,我的类肯定继承自抽象类

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

    }

1 个答案:

答案 0 :(得分:0)

使用 foo(int x){ if (x>=3) return x; else return "less than three"; }

Documentation of IsSubClassOf on MSDN