获取委托中每个方法的返回值及处理委托中的异常

2016-12-23  本文已影响0人  Unity学习的路上

using System;

using System.Text;

namespace Test01

{

public delegate string State();//声明委托

class FanState

{

public string Fan()

{

return "风扇运行良好";

}

}

class ComputerState

{

public string Computer()

{

throw new Exception("电脑过热");//抛出一个异常

}

}

class TVState

{

public string TV()

{

return "电视运行良好";

}

}

class Program

{

static void Main(string[] args)

{

State stateCheck = new State(new FanState().Fan);//将方法添加到委托中

stateCheck += new ComputerState().Computer;//将方法添加到委托中

stateCheck += new TVState().TV;//将方法添加到委托中

Console.WriteLine(Report(stateCheck));//调用方法

}

public static string Report(State s)

{

if (s == null)

{

return null;

}

StringBuilder report = new StringBuilder();//创建一个StringBuider类的一个实例

Delegate[] DelArray = s.GetInvocationList();//这个方法的返回值是一个Delegate类型的数组,每一个委托中只有一个方法

foreach (State item in DelArray)//遍历委托数组

{

try

{

report.AppendFormat("{0}{1}{1}", item(), Environment.NewLine);//字符串拼接

}

catch(Exception e)//处理异常

{

object obj = item.Target;

report.AppendFormat("错误的方法是:{1}{0}错误的信息是{2}{0}错误的方法类型是{3}{0}{0}", Environment.NewLine, item.Method.Name, e.Message, obj.GetType().ToString());

}

}

return report.ToString();

}

}

}

上一篇 下一篇

猜你喜欢

热点阅读