加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何确定是否构造了一个类(实例构造函数已经完成)?

发布时间:2020-12-15 08:38:51 所属栏目:百科 来源:网络整理
导读:我有一个基类,它有一个由派生类执行的方法. 该方法由派生类的构造函数以及其中的某些方法或属性引发. 我需要确定它是来自该派生类的实例构造函数内部还是之后(在运行时). 以下示例说明了我需要的内容: public class Base{ public Base() { } protected void
我有一个基类,它有一个由派生类执行的方法.
该方法由派生类的构造函数以及其中的某些方法或属性引发.
我需要确定它是来自该派生类的实例构造函数内部还是之后(在运行时).

以下示例说明了我需要的内容:

public class Base
{
    public Base()
    {

    }

    protected void OnSomeAction(object sender)
    {
        // if from derived constructor EXIT,else CONTINUE
    }
}

public class Derived : Base
{
    public void Raise()
    {
        base.OnSomeAction(this); // YES if not called by constructor
    }

    public Derived()
    {
        base.OnSomeAction(this); // NO
        Raise(); // NO
    }
}

class Program
{
    static void Main(string[] args)
    {
        var c = new Derived(); // NO (twice)
        c.Raise(); // YES
    }
}

问题是我无法更改签名或参数,因为我无法更改派生类.基本上我的想法是确定派生类(发送者)是否完全构造.

所以实现就是这样.我不能在打破派生类的基类中进行更改.我只能对基类进行更改:/

这有可能以某种方式,好还是不好?不幸的是,即使是一些反思魔法或类似的hacky方法也是受欢迎的,因为这是必须的:/.

谢谢!

解决方法

Is this possible in some way…

good or not?

不.但你已经知道了.

不过,这是一种方法.

protected void OnSomeEvent( object sender,EventArgs e )
{
    var trace = new StackTrace();
    var frames = trace.GetFrames();

    for ( int idx = 0; idx < frames.Length; idx++ )
    {
        MethodBase method;

        method = frames[idx].GetMethod();
        if ( method.ReflectedType == typeof(Derived) && method.IsConstructor )
        {
            return;
        }
    }
    /* Perform action */
}

source

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读