我爲你寫了一個非常簡單的基本解決方案。請閱讀代碼中的註釋以瞭解解決方案。如果有什麼不清楚的地方,請提問。
下面的示例,將導致事件,火災,如果人的名稱更改:
這裏是Person對象:
public class Person
{
//Event to register to, when you want to capture name changed of person
public event EventHandler<NameChangedEventArgs> nameChangedEvent;
//Property
private string _name;
public string Name
{
get { return _name; }
set
{
this._name = value;
//Call the event. This will trigger the OnNameChangedEvent_Handler
OnNameChangedEvent_Handler(new NameChangedEventArgs() {NewName = value});
}
}
private void OnNameChangedEvent_Handler(NameChangedEventArgs args)
{
//Check if event is null, if not, invoke it.
nameChangedEvent?.Invoke(this, args);
}
}
//Custom event arguments class. This is the argument type passed to your handler, that will contain the new values/changed values
public class NameChangedEventArgs : EventArgs
{
public string NewName { get; set; }
}
下面是一個實例,並使用Person對象的代碼:
class Program
{
static void Main(string[] args)
{
//Instantiate person object
var person = new Person();
//Give it a default name
person.Name = "Andrew";
//Register to the nameChangedEvent, and tell it what to do if the person's name changes
person.nameChangedEvent += (sender, nameChangedArgs) =>
{
Console.WriteLine(nameChangedArgs.NewName);
};
//This will trigger the nameChanged event.
person.Name = "NewAndrewName";
Console.ReadKey();
}
}
因爲沒有人在您的活動中註冊 – Rahul
您尚未向您的活動註冊任何處理程序方法,因此在您提出活動時您希望運行什麼? https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-subscribe-to-and-unsubscribe-from-events –
以下鏈接對您有幫助問題: [有或沒有代表的事件](https://stackoverflow.com/questions/1334736/events-with-and-without-delegates-in-asp-net) – Viswa