C# 事件
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace CSharpStudy
{
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
CalculatorManager calculatorManager = new CalculatorManager();
calculator.MyCalculate += calculatorManager.Add;
calculator.Calculate(2, 100);
calculator.MyCalculate += calculatorManager.Substract;
calculator.Calculate(100, 100);
Console.ReadKey();
}
}
public class Calculator
{
public delegate void CalculateEventhandler(object sender, CalculateEventArgs e);
public event CalculateEventhandler MyCalculate;
public virtual void OnCalculate(CalculateEventArgs e)
{
if (MyCalculate != null)
{
MyCalculate(this, e);
}
}
public void Calculate(int x, int y)
{
CalculateEventArgs e = new CalculateEventArgs(x, y);
OnCalculate(e);
}
public class CalculateEventArgs : EventArgs
{
public readonly int x, y;
public CalculateEventArgs(int x, int y)
{
this.x = x;
this.y = y;
}
}
}
public class CalculatorManager
{
public void Add(object sender, Calculator.CalculateEventArgs e)
{
Console.WriteLine(e.x + "+" + e.y);
}
public void Substract(object sender, Calculator.CalculateEventArgs e)
{
Console.WriteLine(e.x + "-" + e.y);
}
}
}
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace CSharpStudy
{
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
CalculatorManager calculatorManager = new CalculatorManager();
calculator.MyCalculate += calculatorManager.Add;
calculator.Calculate(2, 100);
calculator.MyCalculate += calculatorManager.Substract;
calculator.Calculate(100, 100);
Console.ReadKey();
}
}
public class Calculator
{
public delegate void CalculateEventhandler(object sender, CalculateEventArgs e);
public event CalculateEventhandler MyCalculate;
public virtual void OnCalculate(CalculateEventArgs e)
{
if (MyCalculate != null)
{
MyCalculate(this, e);
}
}
public void Calculate(int x, int y)
{
CalculateEventArgs e = new CalculateEventArgs(x, y);
OnCalculate(e);
}
public class CalculateEventArgs : EventArgs
{
public readonly int x, y;
public CalculateEventArgs(int x, int y)
{
this.x = x;
this.y = y;
}
}
}
public class CalculatorManager
{
public void Add(object sender, Calculator.CalculateEventArgs e)
{
Console.WriteLine(e.x + "+" + e.y);
}
public void Substract(object sender, Calculator.CalculateEventArgs e)
{
Console.WriteLine(e.x + "-" + e.y);
}
}
}