저는 C#의 새로운 기능입니다. 방금 대리인 기능을 연구하려고했습니다. 위임자에 대해 읽은 기사와 노트를 기반으로 필자는 노트와 기사에서 이해 한 것을 토대로 대리인을 구현하는 샘플 코드를 작성하려고했습니다.대리자 이벤트 문제
샘플을 실행하는 동안
하지만 오류를 얻고있다 "개체 참조가 개체의 인스턴스로 설정되지 않았습니다를."
여기에 어떤 문제가 있습니까? 또는 델리게이트를 올바른 방식으로 구현 했습니까? 또는 대리인에 대한 내 개념이 잘못 되었습니까? ...
도와주세요. 미리 감사드립니다.
나는 아래 코드를 게시했다.
하여 default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
TestClass myObject = new TestClass();
protected void Page_Load(object sender, EventArgs e)
{
myObject.MyDelegateEvent += new TestClass.MyDelegate(myObject_MyDelegateEvent);
}
void myObject_MyDelegateEvent(object sender, EventArgs e)
{
Console.WriteLine("Delegate event called");
}
}
TestClass에
public class TestClass
{
public delegate void MyDelegate(object sender, EventArgs e);
public event MyDelegate MyDelegateEvent;
public TestClass()
{
MyDelegateEvent(this, null); // Here getting error "Object reference not set to an instance of an object."
}
}
생성자에서 이벤트를 발생시킬 수 없습니다. 객체가 생성 될 때까지 * 어떤 코드도 이벤트 처리기를 구독 할 수 없습니다. 이것은 닭고기와 계란 문제입니다. –