C# 异常统一处理方式
Exception 统一处理
using System; using System.Collections.Generic; using System.Text; namespace WUtility.Common { public class ActionHelper { private static Action<Exception> _dealException; public static event Action<Exception> DealException { add { _dealException += value; } remove { if (_dealException != null) _dealException -= value; } } /// <summary> /// 通用的异常处理 /// </summary> /// <param name="action">对应事件逻辑</param> /// <param name="state">参数值</param> public static void SafeInvoke(Action<object> action, object state) { try { if (action == null) return; action.Invoke(state); } catch (Exception ex)//按异常类型区分处理 { if (_dealException != null) _dealException(ex); } } /// <summary> /// 通用的异常处理 /// </summary> /// <param name="method"></param> /// <param name="obj"></param> public static void SafeInvoke(Delegate method, params object[] obj) { try { if (method == null) return; if (obj.Length == 0) method.DynamicInvoke(null); else if (obj.Length == 1) method.DynamicInvoke(obj[0]); else if (obj.Length == 2) method.DynamicInvoke(obj[0], obj[1]); } catch (Exception ex)//按异常类型区分处理 { if (_dealException != null) _dealException(ex); } } } }
使用示例:
private void button20_Click(object sender, EventArgs e) { ActionHelper.DealException += (obj) => { var szInfo = obj.Message; MessageBox.Show(szInfo); }; var k = 20 - 20; ActionHelper.SafeInvoke((obj) => { MessageBox.Show("SafeInvokeAcion" + (50 / k)); }, null); } private void button21_Click(object sender, EventArgs e) { ActionHelper.SafeInvoke(new TestInvoke(TestSafeInvokeDelegate), "12345", "678910"); } private delegate void TestInvoke(string szInfo, string szInfo2); private void TestSafeInvokeDelegate(string szInfo, string szInfo2) { var info = szInfo + "^" + szInfo2; MessageBox.Show(info); }
posted on 2019-06-05 16:53 K丶Formular 阅读(1112) 评论(0) 编辑 收藏 举报