如何判断构造函数是否被另一个构造函数调用?

时间:2011-12-15 13:47:44

标签: c# constructor

在链接构造函数时,在C#中,如何轻松判断构造函数是否被直接调用,或者是否由另一个构造函数使用this调用?

public Test() : this(string.Empty, string.Empty) {}
public Test(string helloworld) : this(helloworld, string.Empty){}
public Test(string helloworld, string goodbyeworld)
{
   //do work
}

2 个答案:

答案 0 :(得分:2)

如果由于某种原因你真的需要来做这件事(你几乎不需要),可以通过将你的“主”构造函数设为私有或受保护并添加另一个指示哪个参数来实现使用了其他构造函数。

我意识到这是一个荒谬的答案,但问题也有点荒谬。

答案 1 :(得分:0)

这不完全准确,但您可以检查调用堆栈。有关详细信息,请参阅此问题

How can I find the method that called the current method?

相关问题