C sharp事件不起作用 [英] C sharp Event is not working
本文介绍了C sharp事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的Person类中创建一个事件,当 Cash
属性为> = 100时通知其他类。我的代码运行正常,但不是'做任何事情。
I'm trying to make an event in my Person Class that notifies other classes when the Cash
property is >= 100. My code runs fine, but doesn't do anything.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person NewPerson = new Person();
NewPerson.AddCash(150);
NewPerson.Myevent += NewPerson_Myevent;
}
static void NewPerson_Myevent()
{
Console.WriteLine("Hello New Person");
}
}
public class Person
{
public delegate void MyeventHandler();
public event MyeventHandler Myevent;
private int _cash = 50;
public int Cash
{
get
{
return this._cash;
}
set
{
this._cash = value;
if (this._cash >= 100)
{
if (Myevent != null)
{
Myevent();
}
}
}
}
public void AddCash(int money)
{
Cash += money;
}
}
}
推荐答案
您在添加活动之前添加了这笔钱。颠倒代码的顺序
You're adding the money before you attach the event. Reverse the order of the code
Person NewPerson = new Person();
NewPerson.Myevent += NewPerson_Myevent;
NewPerson.AddCash(150);
这篇关于C sharp事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文