C# IsAssignableFrom与IsSubClassOf 判断匿名类是否继承父类

 

 

    public class Dog : Animal
    {
        public string name { get; set; }
    }
    public class Animal
    {
        public string id { get; set; }
    }

    public class Main
    {
        public void Main()
        {
            Dog aa = new Dog { name = "", id = "动物" };
            CheckClass(aa);
        }
        public void CheckClass<T>(T entity)
        {
            bool re1 = typeof(Animal).IsAssignableFrom(typeof(T));
            //返回true的条件是Dog类直接或间接的实现了Animal类;
            bool re2 = typeof(T).IsSubclassOf(typeof(Animal));
            //返回true的条件是Dog类是Animal的子类
            
            var id = (entity as Animal).id;
        }
    }

 

posted @ 2018-12-06 16:37  听雨的人  阅读(6341)  评论(1编辑  收藏  举报