C # abnormal unified approach

Exception unified treatment

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>
        ///General exception handling
         ///  </ Summary> 
        ///  <param name = "Action"> corresponding to the event logic </ param> 
        ///  <param name = "State"> parameters </ param> 
        public  static  void SafeInvoke (the Action < Object > Action, Object State) 
        { 
            the try 
            { 
                IF (Action == null ) return ; 
                action.Invoke (State); 
            } 
            the catch (exception EX) // by distinguishing the type of exception handling 
            {
                 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);
                 The else  IF (obj.Length == . 1 ) 
                    method.DynamicInvoke (obj [ 0 ]);
                 the else  IF (obj.Length == 2 ) 
                    method.DynamicInvoke (obj [ 0 ], obj [ . 1 ]); 
            } 
            the catch ( EX exception) // by distinguishing the type of exception handling 
            {
                 IF ! (_dealException = null ) 
                    _dealException (EX); 
            } 
        } 
    } 
}

 

Example of use:

        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(objectsender, 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);
        }

 

Guess you like

Origin www.cnblogs.com/aisa-thanatos/p/10980552.html