欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 中一些类关系的判定方法

程序员文章站 2022-08-21 11:17:30
1. IsAssignableFrom实例方法 判断一个类或者接口是否继承自另一个指定的类或者接口。 输出结果: IDog was inherited from IAnimalDog was inherited from IAnimalDog was inherited from IDogCate ......

1.  isassignablefrom实例方法 判断一个类或者接口是否继承自另一个指定的类或者接口。

public interface ianimal { }
public interface idog : ianimal { }
public class dog : idog { }
public class cate : ianimal { }
public class parrot { }
    	
var ianimaltype = typeof(ianimal);
var idogtype = typeof(idog);
var dogtype = typeof(dog);
var catetype = typeof(cate);
var parrottype = typeof(parrot);

console.writeline(ianimaltype.isassignablefrom(idogtype)
    ? $"{idogtype.name} was inherited from {ianimaltype.name}"
    : $"{idogtype.name} was not inherited from {ianimaltype.name}");

console.writeline(ianimaltype.isassignablefrom(dogtype)
    ? $"{dogtype.name} was inherited from {ianimaltype.name}"
    : $"{dogtype.name} was not inherited from {ianimaltype.name}");

console.writeline(idogtype.isassignablefrom(dogtype)
    ? $"{dogtype.name} was inherited from {idogtype.name}"
    : $"{dogtype.name} was not inherited from {idogtype.name}");

console.writeline(ianimaltype.isassignablefrom(catetype)
    ? $"{catetype.name} was inherited from {ianimaltype.name}"
    : $"{catetype.name} was not inherited from {ianimaltype.name}");

console.writeline(ianimaltype.isassignablefrom(parrottype)
    ? $"{parrottype.name} inherited from {ianimaltype.name}"
    : $"{parrottype.name} not inherited from {ianimaltype.name}");
console.readkey();

输出结果:

idog was inherited from ianimal
dog was inherited from ianimal
dog was inherited from idog
cate was inherited from ianimal
parrot not inherited from ianimal

2.isinstanceoftype 判断某个对象是否继承自指定的类或者接口

dog d=new dog();
var result=typeof(idog).isinstanceoftype(d);
console.writeline(result? $"dog was inherited from idog": $"dog was not inherited from idog");
console.readkey();

输出结果:

dog was inherited from idog

3.issubclassof 判断一个对象的类型是否继承自指定的类,不能用于接口的判断,这能用于判定类的关系

public interface ianimal { }
public interface idog : ianimal { }
public class dog : idog { }
public class husky : dog { }
public class cate : ianimal { }
public class parrot { }
husky husky = new husky();
var result = husky.gettype().issubclassof(typeof(dog));
console.writeline(result ? $"husky was inherited from dog" : $"husky was not inherited from dog");

输出结果:

husky was inherited from dog

这个方法不能用于接口,如果穿接口进去永远返回的都是false

dog dog = new dog();
var dogresult = dog.gettype().issubclassof(typeof(idog));
console.writeline(dogresult);

结果:

false