<分区>
我在这里创建了这个程序来演示我正在尝试做的事情。您可以看到,除了应调用 _OnSell
事件的那行代码外,所有代码都已编写。 (第 21 行~)
using System;
namespace example
{
public class Car
{
public int Price;
public string ModelName;
private Boolean Sold;
public delegate void SellEventHandler(string str);
public event SellEventHandler _OnSell;
public Boolean _Sold
{
get { return Sold; }
set
{
Sold = value;
if (Sold == true)
{
// INVOKE _OnSell EVENT HERE !!
}
}
}
public void OnSell(string str)
{
Console.WriteLine("library stuff");
}
public Car(int price, string modelname)
{
Price = price;
ModelName = modelname;
Sold = false;
_OnSell = OnSell;
}
}
public class Program
{
static void Main()
{
Program p1 = new Program();
Car _car = new Car(6000, "audi");
_car._OnSell += p1.Car_OnSell;
_car._Sold = Console.ReadLine() == "true" ? true : false;
Console.ReadLine();
}
public void Car_OnSell(string message)
{
Console.WriteLine("user stuff");
}
}
}
每当值 _car._Sold
更改时,我都试图调用事件 _car._OnSell
。我如何在 C# 中做到这一点?