本文介绍了通过字符串比较检查动态对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有某种类型的话,检查基础对象的最佳方式是什么,myObject可以具有n级别的层次结构,我想与字符串进行比较,因为myObject是动态的,而且我没有对车辆的装配访问>

a)汽车:车辆

b)BiCycle:TwoWheeler:车辆

c)卡车:预告片:FourWheeler:车辆

  dynamic myObject = someObject; 
if(myObject is Vehicle)// Works
if(myObject isVehicle)//如何?


解决方案

写了一个递归方法来解决它: p>

  private bool IsVehicle(Type type)
{
if(type.BaseType!= null)
if(type.BaseType.FullName ==Vehicle)
return true;
else
return IsVehicle(type.BaseType);
返回false;
}


What is the best way to check a base object if of certain type, myObject can have hierarchies at "n" level, I want to compare with string because myObject is dynamic and i do not have assembly access to vehicle

a) Car : Vehicle
b) BiCycle : TwoWheeler : Vehicle
c) Truck : Trailer : FourWheeler : Vehicle

dynamic myObject = someObject;
if(myObject is Vehicle)  // Works
if(myObject is "Vehicle") //How to ?
解决方案

Wrote a little recursive method to solve it:

 private bool IsVehicle(Type type)
        {
            if (type.BaseType != null)
                if (type.BaseType.FullName == "Vehicle")
                    return true;
                else
                    return IsVehicle(type.BaseType);
            return false;
        }

这篇关于通过字符串比较检查动态对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 09:39