检测构造函数中的执行 [英] Detect Execution in Constructor

查看:42
本文介绍了检测构造函数中的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我有一个受保护的方法,我只希望从

构造函数中的代码或构造函数调用的方法调用它。如果它没有直接或间接地从构造函数调用

,我想抛出一个异常。无论如何要实现这个吗?


提前致谢!

解决方案

< blockquote>创建只读私人bpp;班上的eam成员。初始化

为true:


private readonly bool _inConstructor = true;


当你的构造函数完成运行时,设置为false:


this._inConstructor = false;


由于只能在构造函数中设置只读成员而且无处可用/>
else,你保证如果_inConstructor为true,你就会运行

构造函数。

嗯...想一想,它运行正常,直到你运行一个子类的

构造函数,此时_inConstructor将是

错误。


为了使这个工作也适用于子课程,你必须使

_inConstructor受到保护,并且在每个子课程开始时

构造函数,说:


this._inConstructor = true;


然后


this._inConstructor = false;


结尾。


不是ver令人满意的解决方案,但是唯一的其他解决方案

走栈(哎呀!)?任何人?


Gniluy写道:

我有一个受保护的方法,我只想从中调用它
构造函数中的代码或构造函数调用的方法中的代码。如果没有直接或间接地从构造函数调用它,我想抛出一个异常。无论如何都要实现这个吗?




除了其他回复之外,我还想提到那些调用

虚拟来自构造函数的代码被许多人视为非常危险的b
实践。尝试谷歌搜索呼叫虚拟构造函数,它会找到你关于这个主题的很多信息。


奥利弗斯特姆

-

omnibus ex nihibo ducendis sufficit unum

插入空格以防止谷歌电子邮件销毁:

MSN oliver @ sturmnet.org Jabber sturm @ amessage.de

ICQ 27142619 http://www.sturmnet .org / blog


Hi,

I have a protected method that I only want it to be called from code in
constructor or from methods called by constructor. If it is not called
directly or indirectly from constructor, I want to throw an exception. Is
there anyway to implement this?

Thanks in advance!

解决方案

Create a "readonly" private bpp;eam member in your class. Initialize it
to true:

private readonly bool _inConstructor = true;

When your constructor finishes running, set it to false:

this._inConstructor = false;

Since a readonly member can be set only in a constructor and nowhere
else, you''re guaranteed that if _inConstructor is true, you''re running
the constructor.


Hmm... thinking this over, it works fine until you''re running the
constructor of a child class, at which point _inConstructor will be
false.

To make this work for child classes, too, you would have to make
_inConstructor protected, and at the start of every child class
constructor, say:

this._inConstructor = true;

and then

this._inConstructor = false;

at the end.

Not a very satisfactory solution, but is the only other solution to
walk the stack (yuck!)? Anyone?


Gniluy wrote:

I have a protected method that I only want it to be called from code in
constructor or from methods called by constructor. If it is not called
directly or indirectly from constructor, I want to throw an exception. Is
there anyway to implement this?



In addition to the other replies, I wanted to mention that calls into
virtual code from constructors are regarded by many as a very dangerous
practice. Try googling for "call virtual constructor", that''ll find you
a lot of information on the topic.

Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog


这篇关于检测构造函数中的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆