当前位置: 移动技术网 > IT编程>开发语言>.net > C# 中一些类关系的判定方法

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

2018年12月27日  | 移动技术网IT编程  | 我要评论

drawtext,师范生招聘,西子书院局长成长史

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网