gpt4 book ai didi

c# - 你能得到 C# 中哪个 child 调用构造函数的信息吗?

转载 作者:行者123 更新时间:2023-12-04 10:14:46 25 4
gpt4 key购买 nike

我正在尝试获取有关哪个 child 称为 parent 构造函数的信息。我不允许将参数传递给构造函数。这样的事情可能吗?

class Parent {
Parent() {
Console.WriteLine("Child1 called me");
}

}
class Child1: Parent {
string name;
Child1(string name) {
this.name = name;
}

}
class Child2: Parent {
string surname;
Child1(string surname) {
this.surname = surname;
}

}

最佳答案

GetType()仍然可以在这里工作,并且不是 virtual (这限制了重新初始化字段的麻烦,这是从构造函数调用 virtual 方法时的问题);如果涉及多种类型,您始终可以探索树:

    public Parent()
{
var type = GetType();
while (type != typeof(Parent) && type != null)
{
Console.WriteLine(type.Name);
type = type.BaseType;
}
}

如果我们有:

class Child3 : Child2
{
public Child3(string surname) : base(surname) { }
}
// ...
new Child3("whatever");

然后这将输出:
Child3
Child2

关于c# - 你能得到 C# 中哪个 child 调用构造函数的信息吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61124378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com