繁体   English   中英

c#中的事件和委托:如何使用事件和委托来通知一个类有关另一类的更改

[英]Events and Delegates in c# : How to use Events & Delegates to Notify One class about changes in other class

问题在于使用事件和委托使用B:Show()引发的B:Show()类事件调用A:Show1()类方法的正确方法以下

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");            
    }
}

抱歉有任何错误,这是我第一次stackoverflow

不能想到您要完成的任务,但是回答您的问题可能会做到。 除非我不明白你的问题对。
请注意,这违反了OOP的原则,该原则指出每个类都应独立于其他类。

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

public class classB
{
    public void show()
    {
        new classA().show1(); 
        Console.WriteLine("I am class B");            
    }
}

要从已编辑的问题中获取结果,可以使用以下代码:

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()方法中,您也可以这样做:

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

但是您不应该同时执行这两个操作,否则将导致无限循环,最终导致stackoverflow

我想这就是答案@GuidoG @Kai Thoma

class A
{
    public A(B b)
    {
        b.ShowA += new methcall(this.showA);
    }
    public void showA()
    {
        Console.WriteLine("I am Class A");
    }
}
class B
{
    public event methcall ShowA;
    public void showB()
    {
        Console.WriteLine("I am Class B");
        if (ShowA != null)
            ShowA();
    }
}
class Program
{
    static void Main()
    {
        B b = new B();
        A a = new A(b);
        methcall m = new methcall(b.showB);
        m.Invoke();
        Console.ReadKey();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM