c#中的事件和代表:如何使用事件&代表通知一个班级关于其他班级的变化

时间:2016-10-10 05:21:33

标签: c# winforms console

问题在于使用事件和放大器的正确方法。代表使用在A:Show1()

中引发的B类事件来调用类B:Show()的方法
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

3 个答案:

答案 0 :(得分:1)

不能想到你想要完成什么,但回答你的问题,这可能会做到。除非我不明白你的问题 请注意,这违反了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");            
    }
}

答案 1 :(得分:1)

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

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();

但你不应该同时做这两件事,否则你会在堆栈溢出中得到无限循环

答案 2 :(得分:0)

我猜这是@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();
    }
}