获取嵌套派生类(C#)的父级的名称

本文关键字:嵌套 派生 获取 | 更新日期: 2023-09-27 18:09:23

示例。如何在嵌套类中获取名称"Parent"。嵌套类可以在任何类中初始化并获取其名称。

public class Parent
{
    public ParentNested n = new ParentNested();
}
public class Nested
{
    public Nested()
    {
        // return "Parent" ???
        string ParentName = GetParentClassName();
    }
}
public class ParentNested : Nested { }

获取嵌套派生类(C#)的父级的名称

忽略与设计相关的问题,可以使用反射获取信息;

    public Nested()
    {
        Type type;
        for (int i = 1;; i++)
        {
            // Get the method in the i'th stack frame
            var method = new StackFrame(i).GetMethod();
            if (method == null) return;
            // Get the class declaring the method
            type = method.DeclaringType;
            if (type == null) return;
            // If the class isn't a parent class, use it.
            if (!type.IsSubclassOf(typeof(Nested)))
                break;
        }
        _parent = type.FullName;    // Will be set to "Parent"
    }

这个简单的版本将在调用堆栈中查找第一个非基类,并将其保存到_parent中。

所以您想让Nested类的实例找出谁"拥有"它们?

既然这个问题带有"反思"的标签,我只想说,你不能用反思来做这件事。

但是,如果Nested的实例在逻辑上需要知道拥有它们的对象,那么您需要告诉它们。您可以将所有者的实例(Parent(传递给Nested的实例,如下所示:

public class Parent
{
    public ParentNested n;
    public Parent()
    {
         n = new ParentNested(this);    
    }
}
public class Nested
{
    public Nested(object owner)
    {
        // return "Parent" ???
        string ParentName = owner.GetType().Name;
    }
}
public class ParentNested : Nested
{
    public ParentNested(object owner) : base(owner) {}
}

现在是这样使用的。但在许多地方都需要使用带有参数"this"的构造函数。用作任何类的参数都是有限的接口。但是嵌套类继承考虑了另一个设计器和编写。

public interface IParent { }
public class Parent : IParent
{
    public ParentNested n;
    public Parent()
    {
        n = new ParentNested(this);
    }
}
public class Nested
{
    private IParent _parent;
    public Nested(IParent parent)
    {
        // return "Parent"
        _parent = parent;
    }
}
public class ParentNested : Nested
{
    public ParentNested(IParent parent) : base(parent) { }
}