调用类的非静态方法,而无需使用代理和事件对其进行初始化 [英] call a nonstatic method of class without initializing it using delegates and events

查看:130
本文介绍了调用类的非静态方法,而无需使用代理和事件对其进行初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是如果有 A:show1()并且有类 B:show()
我必须在类B中调用 show1(),而不使用A类对象使用委托和事件我试过以下:

The question is if there is class A:show1() and there is class B:show() I have to call show1() in class B without using class A object using delegates and events I have tried following:

public class classA
{
    private classB _Thrower;

    public classA()
    {
        _Thrower = new classB();            
        _Thrower.ThrowEvent += (sender, args) => { show1(); };
    }

    public void show1()
    {
        Console.WriteLine("I am class 2");
    }
}

public class classB
{
    public delegate void EventHandler(object sender, EventArgs args);

    public event EventHandler ThrowEvent = delegate { };
    public classB()
    {
        this.ThrowEvent(this, new EventArgs());
    }
    public void show()
    {
        Console.WriteLine("I am class 1");            
    }
}

对不起,任何错误,这是我第一次of stackoverflow

Sorry for any mistakes in question this is my first time of stackoverflow

推荐答案

要获得已编辑问题的结果,您可以使用以下代码:

To get the result from your edited question you can use this code:

static void Main()
{
    classA obA = new classA();
    classB obB = new classB();
    obA.Shown += ( object sender, EventArgs e ) => { obB.ShowB(); };
    obA.ShowA();
}

public class classA
{
    public event EventHandler Shown;

    public classA()
    {
    }

    public void ShowA()
    {
        Console.WriteLine( "I am class A" );

        if( Shown != null )
            Shown( this, EventArgs.Empty );
    }
}

public class classB
{
    public event EventHandler Shown;

    public classB()
    {
    }

    public void ShowB()
    {
        Console.WriteLine( "I am class B" );

        if( Shown != null )
            Shown( this, EventArgs.Empty );
    }
}

main / code>方法,你也可以反过来:

In main() method you could do it vica versa as well:

obB.Shown += ( object sender, EventArgs e ) => { obA.ShowA(); };
obB.ShowB();

但是你不应该同时做这两个,否则会得到一个无限循环stackoverflow

But you should not do both at the same time or you'll get an infinite loop ending up in a stackoverflow

这篇关于调用类的非静态方法,而无需使用代理和事件对其进行初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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