繁体   English   中英

在C#中引发事件-需要帮助

[英]Raise events in c# - help needed

您好,我正在尝试引发一个人的生日大于实际日期的事件。

我是事件的新手,似乎不起作用。

代码在下面,

namespace LibClassLuchthaven
{
    public class Person
    {

        public DateTime Birthdate { get; set; }

        public string Firstname { get; set; }
        public Gender Gender { get; set; }
        public string Name { get; set; }

        public event EventHandler BirthdateInFuture;

        public Person()
        {
            this.Birthdate = DateTime.Now;
            this.Firstname = string.Empty;
            this.Gender = Gender.unknown;
            this.Name = string.Empty;
        }
        public Person(DateTime birthdate, string firstname, Gender gender, string name)
        {
            this.Birthdate = birthdate;
            this.Firstname = firstname;
            this.Gender = gender;
            this.Name = name;
        }
        public void OnBirthdateInFuture()
        {

            if (BirthdateInFuture!=null)
            {
                if (this.Birthdate > DateTime.Now)
                {
                    BirthdateInFuture(this, EventArgs.Empty);
                }

            }

        }


        public override string ToString()
        {
            return  this.Name + ", " + this.Firstname + " - " + this.Birthdate + " ( +" + this.Gender + ")";
        }
    }
}

public partial class FormCrewManagement : Form
{

    public Person person = new Person();


    public FormCrewManagement()
    {
        InitializeComponent();

        person.BirthdateInFuture += Person_BirthdateInFuture;

    }

    private void Person_BirthdateInFuture(object sender, EventArgs e)
    {
        MessageBox.Show("Birthdate is in the future");
    }

尝试更改属性

public DateTime Birthdate { get; set; }

private DateTime _birthDate;
public DateTime Birthdate 
{ 
   get {return _birthDate;} 
   set
   {
      _birthDate=value;
      if(value > DateTime.Now)
         BirthdateInFuture?.Invoke(this, EventArgs.Empty);
   } 
}

当生日值为将来时,这将引发事件。

看来问题可能是合乎逻辑的,而不是与事件有关的问题。 您正在将生日设置为今天的日期,然后检查是否晚些。 永远不会。

public Person()
{
    this.Birthdate = DateTime.Now;

    if (BirthdateInFuture!=null)
    {
        if (this.Birthdate > DateTime.Now)
        {
            BirthdateInFuture(this, EventArgs.Empty);
        }
    }

菲利普(Philip),在您的代码中没有引发事件的地方。 您可以创建一个名为BirthDate的属性,然后在设置器部分中引发事件。 当生日更改为将来的日期时,它将/将引发该事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM