c# - 从嵌套类中获取周围类的名称

标签 c# .net-2.0

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

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

这在 C# 中可行吗?

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

最佳答案

像这样应该解析出外部类的名称:

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;

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

关于c# - 从嵌套类中获取周围类的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228855/

相关文章:

c# - 如何使用 Microsoft Graph API c# SDK 在 DriveItem 上获取 Sharepoint ListItem

.net-2.0 - 使用 yield 迭代数据读取器可能不会关闭连接?

architecture - 客户端(桌面应用程序)提取数据......但我希望服务器(网络应用程序)推送数据

c# - C#异常处理程序继续下一个

c# - ANTLR 的 AST 树更新

c# - 反序列化动态 JSON 响应

encryption - Compact Framework - 获取存储卡序列号

c# - 用于 winforms 的 MVP 框架

.net-4.0 - 将 .Net 2.0 项目升级到 .Net 4.0

c# - 使用 C# 6 简化条件表达式