我使用C#,我想从一个类中触发事件:C#触发事件
所以,如果一个类的Price
财产被改变,那么事件onPriceChanged
(类外)应该被解雇。 但是,我收到一个错误:
The name 'onPriceChanged' does not exist in the current context
我该如何解决这个问题? (我想我可以在事件处理程序传递给通过构造方法的类...但如果可能的话我宁愿不要在事件处理程序传递给类)
这里是我的代码:
using System;
public delegate void delEventHandler();
class clsItem
{
//private static event delEventHandler _show;
private delEventHandler _show;
private int _price;
public clsItem() //Konstruktor
{
_show += new delEventHandler(Program.onPriceChanged); // error here : The name 'onPriceChanged' does not exist in the current context
}
public int Price
{
set
{
_price = value;
_show.Invoke(); //trigger Event when Price was changed
}
}
}
class Program
{
static void Main()
{
clsItem myItem = new clsItem();
myItem.Price = 123; //this should trigger Event "onPriceChanged"
}
//EventHandler
public static void onPriceChanged()
{
Console.WriteLine("Price was changed");
}
}
'_show + =新delEventHandler(Program.onPriceChanged);' – 2016-07-26 12:13:40
onPriceChanged是在不同的类(计划)。 – ohadinho
你正在做什么事情的完全相反。 clsItem类不应该知道谁在监听它的事件。换句话说,'clsItem'应该公开一个公共事件,并且在创建新的实例之后,您应该在'Main'方法中附加处理程序。 – Groo