从嵌套 class 中获取周围 class 的名称

Get name of surrounding class from within nested class

我在外部 class 和内部 class 中有一个嵌套的 class 我想通过反射获取外部 class 的名称运行时间。

public abstract class OuterClass // will be extended by children
{
    protected class InnerClass // will also be extended
    {
        public virtual void InnerMethod()
        {
            string nameOfOuterClassChildType = ?;
        }
    }
}

这在 C# 中可行吗?

编辑:我应该补充一点,我想使用反射并从扩展自 OuterClass 的子 class 获取名称,这就是原因,我不知道编译时的具体类型.

这样的东西应该解析出外部的名称 class:

public virtual void InnerMethod()
{
    Type type = this.GetType();

    // type.FullName = "YourNameSpace.OuterClass+InnerClass"

    string fullName = type.FullName;
    int dotPos = fullName.LastIndexOf('.');
    int plusPos = fullName.IndexOf('+', dotPos);
    string outerName = fullName.Substring(dotPos + 1, plusPos - dotPos - 1);

    // outerName == "OuterClass", which I think is what you want
}

或者,正如@LasseVKarlsen 所建议的那样,

string outerName = GetType().DeclaringType.Name;

...这实际上是一个更好的答案。