2017-10-15 9 views
-1

こんにちは私は、人の生年月日が実際の日付よりも大きいときにイベントを起こそうとしています。C#でイベントを発生させる - ヘルプが必要

私はイベントで新しく、うまくいかないようです。コードの下にある

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"); 
    } 
+0

"動作していない"と正確にはどういう意味ですか? –

+2

あなたはどこでも 'OnBirthdateInFuture'を呼び出すようには思われません –

+0

あなたはある時点でOnBirthdateInFutureメソッドを呼び出す必要があります。 – Seb

答えて

0

それはむしろ、イベントとは何よりも、論理的なものであってもよいの問題のように見えます。あなたは今日の日付に誕生日を設定しています...それが後であるかどうかを確認しています。それは決してありません。

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

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

生年月日値は、将来のときにイベントを発生させます

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

これにプロパティ

public DateTime Birthdate { get; set; } 

を変更してみてください。

0

フィリップ、 イベントが発生するコードの場所がありません。 BirthDateという名前のプロパティを作成し、setterの部分でイベントを発生させることができます。生年月日が将来の日付に変更されると、イベントが発生する可能性があります。

関連する問題