1. 委托事件练习:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
delegate void MyDelegate();
class D
{
public event MyDelegate myEvent;
private int score;
public int Score
{
set{score = value;}
get { return score; }
}
public void Output()
{
Console.WriteLine("Score=" + Score);
}
public void SetEvent()
{
myEvent();
}
public D(int a)
{
Score = a; // 为score赋值
}
}
class Program
{
public static void Fun()
{
Console.WriteLine("运行了Fun方法");
}
public static void Main(string[] args)
{
Console.WriteLine("请设置score值(整数):");
int _score = int.Parse(Console.ReadLine());
D d1 = new D(_score);
D d2 = new D(_score);
d1.myEvent += Fun;
d2.myEvent += d2.Output;
d1.SetEvent();
d2.SetEvent();
Console.ReadKey(true); // 停顿作用
}
}
}
运行截图

2. 异常处理练习:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 异常处理
{
class Program
{
static void Main(string[] args)
{
double a, b,c;
Console.WriteLine("请分别输入a,b的值:");
try
{
a = double.Parse(Console.ReadLine());
try
{
b = double.Parse(Console.ReadLine());
if (b == 0.0) throw new DivideByZeroException("除数不能为0!");
}
catch (DivideByZeroException e)
{
throw e;
}
c = a / b;
}catch(FormatException fe){
Console.WriteLine(fe.Message);
Console.WriteLine(fe.StackTrace);
}
}
}
}
运行截图


3. 异常处理练习_图形界面:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 异常处理__窗体程序
{
public partial class Form1 : Form
{
double a, b,c;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
a = double.Parse(textBox1.Text);
}
catch(Exception)
{
MessageBox.Show("输入的数据不符合规范!");
textBox1.Text = "";
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
try
{
string b_str = textBox2.Text;
b = double.Parse(b_str);
if (b == 0.0) throw new DivideByZeroException(); // 手动抛出异常
}
catch (FormatException)
{
// 测试代码
// MessageBox.Show(ex.GetType().ToString());
MessageBox.Show("输入的数据不符合规范!");
textBox2.Text = "";
}
catch (DivideByZeroException)
{
MessageBox.Show("除数不能为0!");
textBox2.Text = "";
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
c = a / b;
textBox3.Text = c.ToString();
}
}
}
运行截图
当输入数据为字符是,捕捉FormatExcetion异常:

当除数为0时,捕捉除零异常:

本文介绍了C#中的委托事件、异常处理基础以及在图形界面程序中的应用。通过实例展示了如何设置委托事件并触发函数,以及如何使用try-catch处理格式错误和除零异常。还涉及到了图形界面程序中用户输入验证的异常捕获。

1514

被折叠的 条评论
为什么被折叠?



