using System;
namespace ThrowExceptionDemo
{
class Program
{
static void Main(string[] args)
{
TestClass test = new TestClass()
{
Text = "非常成功"
};
//如果在调用TestMethod()方法前不指定Test_TestEvent()方法会抛出异常
test.TestEvent += Test_TestEvent;
test.TestMethod();
Console.ReadLine();
}
private static void Test_TestEvent(object sender, EventArgs e)
{
Console.WriteLine("事件不为空,未抛出异常");
}
}
public delegate void TestDelegate(object sender, EventArgs e);//委托
public class TestClass
{
public event TestDelegate TestEvent;//事件
private string text;
public string Text
{
get { return text; }
set { text = value; }
}
private void OnTest()
{
TestDelegate ae = TestEvent;
if (ae != null)
{
ae(this, EventArgs.Empty);
}
else
{
throw new Exception("The method or operation is not implemented.");
}
}
public void TestMethod()
{
OnTest();//激发事件
Console.WriteLine("测试完成," + text);
}
}
}
C#委托事件-抛出事件null异常
最新推荐文章于 2022-08-16 12:43:57 发布