.net 使用反射获取父类的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1524562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:25:08  来源:igfitidea点击:

Getting parent class' name using Reflection

.netreflection

提问by AndreyAkinshin

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

如何使用反射获取某个类的父类的名称?

回答by Maximilian Mayerl

Like so:

像这样:

typeof(Typ).BaseType.Name

回答by Craig Celeste

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

我来到这个问题寻找声明嵌套类的类,即 DeclaringType。

this.GetType().DeclaringType.Name

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

也许不是 OP 所要求的,但也许其他人带着与我相同的搜索条件来到这里。;-)

回答by Graviton

obj.GetType().BaseType.Name

回答by Razzie

You can use:

您可以使用:

string baseclassName = typeof(MyClass).BaseType.Name;

回答by JDunkerley

        Type type = obj.GetType();
        Type baseType = type.BaseType;
        string baseName = baseType.Name;

回答by David

The question above is asking about the Parent Type, which can be retrieved using:

上面的问题是询问父类型,可以使用以下方法检索:

yourRefVar.GetType().UnderlyingSystemType.Name

yourRefVar.GetType().UnderlyingSystemType.Name

回答by lukiasz

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

当前在 .NET Core 中,BaseType 不可用,您可以通过以下方式检索它:

typeof(T).GetTypeInfo().BaseType

回答by Oliamster

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 typeis a class or an interface.

我想添加更多细节,以防您需要找到您班级的最终父类,此代码可能会有所帮助。我认为我不知道它type是一个类还是一个接口。

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;