Compiling and running the above C # program will produce the following results:
Welcome to TipsMake.com
Example 2
This example provides a simple application to troubleshoot a pot system over hot water. When the boiler maintenance engineer, boiler temperature and pressure are automatically recorded in a log file along with the notes of this maintenance engineer.
The program will be as follows:
using System ;
using System . IO ; namespace QTMCsharp { class Boiler { private int temp ; private int pressure ; public Boiler ( int t , int p ) { temp = t ; pressure = p ; } public int getTemp () { return temp ; } public int getPressure () { return pressure ; } } class DelegateBoilerEvent { public delegate void BoilerLogHandler ( string status ); //định nghĩa sự kiện dựa vào delegate trên public event BoilerLogHandler BoilerEventLog ; public void LogProcess () { string remarks = "OK!" ; Boiler b = new Boiler ( 100 , 12 ); int t = b . getTemp (); int p = b . getPressure (); if ( t > 150 || t < 80 || p < 12 || p > 15 ) { remarks = "Cần duy trì" ; } OnBoilerEventLog ( "Thông tin bản ghi:n" ); OnBoilerEventLog ( "Nhiệt độ: " + t + "nÁp suất: " + p ); OnBoilerEventLog ( "nThông báo: " + remarks ); } protected void OnBoilerEventLog ( string message ) { if ( BoilerEventLog != null ) { BoilerEventLog ( message ); } } } class BoilerInfoLogger { FileStream fs ; StreamWriter sw ; public BoilerInfoLogger ( string filename ) { fs = new FileStream ( filename , FileMode . Append , FileAccess . Write ); sw = new StreamWriter ( fs ); } public void Logger ( string info ) { sw . WriteLine ( info ); } public void Close () { sw . Close (); fs . Close (); } } class TestCsharp { static void Logger ( string info ) { Console . WriteLine ( info ); } static void Main ( string [] args ) { Console . WriteLine ( "Ví dụ minh họa sự kiện trong C#" ); Console . WriteLine ( "-------------------------------" ); BoilerInfoLogger filelog = new BoilerInfoLogger ( "e:boiler.txt" ); DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent (); boilerEvent . BoilerEventLog += new DelegateBoilerEvent . BoilerLogHandler ( Logger ); boilerEvent . BoilerEventLog += new DelegateBoilerEvent . BoilerLogHandler ( filelog . Logger ); boilerEvent . LogProcess (); Console . ReadLine (); Console . ReadKey (); filelog . Close (); } } }
And when you run this program you will get results:
Example illustrating events in C #
-------------------------------
Record information:
Temperature: 100
Pressure: 12
Notice: OK!
According to Tutorialspoint
Previous article: Delegate in C #
Next article: Collection in C #