C#对象类型比较 [英] C# Object Type Comparison

查看:234
本文介绍了C#对象类型比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能比较类型声明为两个对象。



我想知道,如果两个对象都是从同一个基类的同类型或。



任何帮助表示赞赏。



例如

 私人布尔AreSame(A型,b型){

}


解决方案

A b 是的两个对象。如果你想看看 A B 在同一个继承层次,然后使用 Type.IsAssignableFrom

  VAR T = a.GetType(); 
变种U = b.GetType();

如果(t.IsAssignableFrom(U)|| u.IsAssignableFrom(T)){
// x.IsAssignableFrom(Y)返回true,如果:
//(1 )x和y是相同类型
//(2)x和y是在相同的继承层次
//(3)y的由x
实施//(4)y的是一个泛型类型参数和其制约因素之一是X
}

如果你想检查是否一个是基类等,然后尝试 <$ C $的C> Type.IsSubclassOf



如果您知道具体的基类,那么就使用关键字:

 如果(一个是T&放大器;和b为T ){
//对象的类型都是T.
的}

否则,你必须直接走继承层次。


How can I compare the types of two objects declared as type.

I want to know if two objects are of the same type or from the same base class.

Any help is appreciated.

e.g.

private bool AreSame(Type a, Type b) {

}

解决方案

Say a and b are the two objects. If you want to see if a and b are in the same inheritance hierarchy, then use Type.IsAssignableFrom:

var t = a.GetType();
var u = b.GetType();

if (t.IsAssignableFrom(u) || u.IsAssignableFrom(t)) {
  // x.IsAssignableFrom(y) returns true if:
  //   (1) x and y are the same type
  //   (2) x and y are in the same inheritance hierarchy
  //   (3) y is implemented by x
  //   (4) y is a generic type parameter and one of its constraints is x
}

If you want to check if one is a base class of the other, then try Type.IsSubclassOf.

If you know the specific base class, then just use the is keyword:

if (a is T && b is T) {
  // Objects are both of type T.
}

Otherwise, you'll have to walk the inheritance hierarchy directly.

这篇关于C#对象类型比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆