In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章将为大家详细讲解有关c#如何实现委托中异常的处理,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
基本委托写法: public delegate double Mathresult(double number);
public class MyMath
{
public static double mathNumber(double number)
{
return number*2;
}
}
使用:
Mathresult m=MyMath. mathNumber;
Console.Write(m(5));
输出结果:10
在委托中,系统提供了2种定义好的委托方法; Action和Func.
他们的区别是:Action不能有返回值,Func可以有返回值。
例如:用Func实现上面的方法。
Func Mathresult = MyMath. mathNumber ;
Console.Write(m(5));
输出结果:10
用Action怎么实现呢??Action是不能有返回值的。只进不出。IN
Action Mathresult = MyMath. mathNumber ;
相应的,mathNumber方法就不能有返回值,需要修改为:
public class MyMath
{
public static double mathNumber(double number)
{
Console.Write(number*2);
}
}
Mathresult (5);
输出结果:10
如果想要有多个委托的话,可以使用数组,同时委托也支持+= -+。
方法Account有2个方法,支出,和查询
class Account
{
decimal acc;
//查询
public public decimal Acc{get; private set;}
public Account(decimal money) { this.Acc=money; }
//支出
public static void Payin(decimal money)
{
if(Acc > = money)
{
Acc+money;
}
else
{
throw new Exception("可用金额不足!");
}
}
//查询余额
public static void Check(decimal money)
{
Console.write("您的余额"+Acc.Tostring());
}
}
给委托提供这两个方法:
一、
Action[] action={Account.Payin,Account.Check};
foreach(Acount a in action)
{
a(100);
a(200);
}
输出结果:
您的余额100
您的余额300
二、
Action action=Account.Payin;
action+=Account.Check;
action(100); action(200);
或:
Action action1=Account.Payin;
Action action2=Account.Check;
Action action3=action1+action2;
action(100); action(200);
判断异常:
Delegate[] de = action3.GetInvocationList();
foreach (Action a in de)
{
try
{
action(100);
a(200);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
关于"c#如何实现委托中异常的处理"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.