如何知道调用了哪个构造函数来创建对象实例
本文关键字:构造函数 创建对象 实例 何知道 调用 | 更新日期: 2023-09-27 18:34:54
我想知道是否有可能知道调用了哪个构造函数来创建对象的实例。例如:
public class Dog
{
public string Name;
public int Age;
public Dog(){}
public Dog(string n, int age)
{
this.Name = n;
this.Age = age;
}
public Dog(string n)
{
this.Name = n;
}
}
现在我创建一个类实例:
var dog = new Dog("pippo", 10);
现在(我认为经过反思(我想从"var dog"中知道我使用哪个构造函数来创建 Dog 实例,如果该类有多个,可能吗?
谢谢。
public enum UsedConstructor { Default, Name, NameAndAge };
public class Dog
{
UsedConstructor UsedConstructor { get; }
public string Name;
public int Age;
public Dog()
{
UsedConstructor = UsedConstructor.Default;
}
public Dog(string n, int age)
{
UsedConstructor = UsedConstructor.NameAndAge;
this.Name = n;
this.Age = age;
}
public Dog(string n)
{
UsedConstructor = UsedConstructor.Name;
this.Name = n;
}
不,这是不可能的,也应该没有必要知道调用了哪个构造函数。如果你在那个构造函数中,你已经知道你在哪里。如果你在计算代码中,你也知道你调用了什么构造函数。
您可以将相关信息存储在变量中。例如:
bool dogWithAge = true;
var dog = new Dog("pippo", 10);
// ....
if(dogWithAge)
{...}
else
{...}
如果它是如此重要,以至于你需要知道狗是否是按年龄创建的,你也可以修改类。
public class Dog{
public string Name { get; set; } // use public properties not fields
public int Age { get; set; } // use public properties not fields
//...
public bool IsAgeKnown { get; set; }
public Dog(string n, int age){
this.IsAgeKnown = true;
this.Name = n;
this.Age = age;
}
}
现在,您始终可以检查该属性:if(dog.IsAgeKnown) ...
在这种情况下有效的另一种方法:使用Nullable<int>
而不是int
。然后你可以使用 if(dog.Age.HasValue)
.
如果你想知道在运行时,你可以在这个对象中设置一个标志。如果在调试中 - 在两个构造函数中设置断点。
public class Dog{
public string Name;
public int Age;
public string CreatedBy;
public Dog(){
this.CreatedBy = "parameterless constructor";
}
public Dog(string n, int age){
this.Name = n;
this.Age = age;
this.CreatedBy = "two parameters constructor";
}
public Dog(string n){
this.Name = n;
this.CreatedBy = "one parameter constructor";
}
}
您也可以使用枚举。