Check dynamic object type by string comparison

前端 未结 2 1786
温柔的废话
温柔的废话 2021-01-21 07:34

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

相关标签:
2条回答
  • 2021-01-21 08:05

    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;
            }
    
    0 讨论(0)
  • 2021-01-21 08:16

    you could use IsAssginableFrom

    System.Type.GetType(typeNameAsString).IsAssignableFrom(myObject.GetType())
    

    that test whether myObject can be assign to a storage location of the type identified by the name (a string) held in typeNameAsString.

    This will only work for types that are actually loaded and you should use the fully qualified name.

    0 讨论(0)
提交回复
热议问题