获取嵌套派生类(C#)的父类的名称
例如。如何在嵌套类中获取名称“Parent”。 嵌套类可以在任何类中初始化并获取其名称获取嵌套派生类(C#)的父类的名称,c#,class,reflection,nested,parent,C#,Class,Reflection,Nested,Parent,例如。如何在嵌套类中获取名称“Parent”。 嵌套类可以在任何类中初始化并获取其名称 public class Parent { public ParentNested n = new ParentNested(); } public class Nested { public Nested() { // return "Parent" ??? string ParentName = GetParentClassName(); }
public class Parent
{
public ParentNested n = new ParentNested();
}
public class Nested
{
public Nested()
{
// return "Parent" ???
string ParentName = GetParentClassName();
}
}
public class ParentNested : Nested { }
所以你想让嵌套的
类的实例找出谁“拥有”它们
既然这个问题被贴上了“反射”的标签,让我说你不能用反射来做这件事
但是如果嵌套的实例在逻辑上需要知道拥有它们的对象,那么您需要告诉它们。您可以将所有者的实例(Parent
)传递给嵌套的实例,如下所示:
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) { }
}
忽略与设计相关的问题,您可以使用反射获取信息
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没有任何父类?您的代码或问题是否正确?需要获取初始化内部类(变量)所在的类的名称。我认为只有使用跟踪才能做到这一点。但这会更容易一些。这个选项是被使用和理解的。但我不想打电话(这个)。你想限制它,而不是“this”,不能使用任何其他类型。我想在所使用的示例中将其显示为一个选项,但并没有使代码复杂化。@Clevelus正如我所说,对象不知道是谁创建了它。没有什么“把戏”可以用来创造你想要的限制。编译器只能帮助你到目前为止-从那时起,你就靠自己了。是的。那么就用trace?@Clevelus如果说“trace”,你的意思是把这个
传递给嵌套的
的实例,那么就可以了。而且,在我看来,你是在跨越重重障碍来解决一个问题,而这个问题最好通过重新思考整体设计来解决。谢谢。如果修改,它可能是解决方案。