Getting parent class' name using Reflection

前端 未结 8 801
后悔当初
后悔当初 2020-12-03 16:30

How can I get the name of the parent class of some class using Reflection?

相关标签:
8条回答
  • 2020-12-03 17:06

    I came to this question seeking the class which declares a nested class, which is the DeclaringType.

    this.GetType().DeclaringType.Name
    

    Maybe not what the OP asked, but maybe someone else comes here with the same search criteria as me. ;-)

    0 讨论(0)
  • 2020-12-03 17:07

    Like so:

    typeof(Typ).BaseType.Name
    
    0 讨论(0)
  • 2020-12-03 17:07
    obj.GetType().BaseType.Name
    
    0 讨论(0)
  • 2020-12-03 17:10

    I would like to add some more details, in case you need to find the ultimate parent class of your class, this code could help. I consider that I don't know whether the type is a class or an interface.

    do
    {
        if (type.IsInterface)
            if (type.BaseType == null)
                break;
    
        if (type.IsClass)
            if (type.BaseType == typeof(object))
                break;
    
        type = type.BaseType;
    
    } while (true);
    
    string ultimateBaseTypeName = type.Name;
    
    0 讨论(0)
  • 2020-12-03 17:11
            Type type = obj.GetType();
            Type baseType = type.BaseType;
            string baseName = baseType.Name;
    
    0 讨论(0)
  • 2020-12-03 17:13

    Currently in .NET Core, BaseType is not available, you can retrieve it by:

    typeof(T).GetTypeInfo().BaseType
    
    0 讨论(0)
提交回复
热议问题