Finished Defining an Event & Subscribing to an Event

building_types
Jason Zhu 2021-02-22 11:25:40 +00:00
parent 4623c69c69
commit 2b07530bb3
2 changed files with 21 additions and 0 deletions

View File

@ -3,6 +3,8 @@ using System.Collections.Generic;
namespace GradeBook
{
public delegate void GradeAddedDelegate(object sender, EventArgs args);
public class Book
{
private List<double> grades;
@ -27,6 +29,12 @@ namespace GradeBook
if (grade <= 100 && grade >= 0)
{
this.grades.Add(grade);
if (GradeAdded != null)
{
// Somebody is listening/subscribing
GradeAdded(this, new EventArgs()); // sender = this, pass; Raising event
}
} else
{
throw new ArgumentException($"Invalid {nameof(grade)}");
@ -52,6 +60,8 @@ namespace GradeBook
}
}
public event GradeAddedDelegate GradeAdded;
public Statistics GetStatistics()
{
var result = new Statistics();

View File

@ -14,6 +14,11 @@ namespace GradeBook
// book.AddGrade(87.2);
var book = new Book("Jason's Grade Book");
book.GradeAdded += OnGradeAdded;
book.GradeAdded += OnGradeAdded;
book.GradeAdded -= OnGradeAdded;
book.GradeAdded -= OnGradeAdded;
string input;
while (true)
@ -54,5 +59,11 @@ namespace GradeBook
Console.WriteLine($"The highesst grade is {stats.highGrade}");
Console.WriteLine($"The average grade is {stats.Average:N1}");
}
static void OnGradeAdded(object sender, EventArgs e)
{
// Main is static, so it can only call static methods, hence return type is static
Console.WriteLine("A line has added");
}
}
}