Release Validator

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Rocky
{
    /// <summary>
    /// Release下会忽略此类所有方法
    /// </summary>
    [DebuggerStepThrough]
    public static class Validator
    {
        #region Fields
        public const string DebugSymbal = "DEBUG";
        #endregion

        #region Methods
        [Conditional(Validator.DebugSymbal)]
        public static void ThrowArgumentNullException(object arg, string paramName = null)
        {
            if (arg == null)
            {
                if (paramName == null)
                {
                    paramName = string.Empty;
                }
                Debug.Assert(false, paramName);
                throw new ArgumentNullException(paramName);
            }
        }

        [Conditional(Validator.DebugSymbal)]
        public static void ThrowArgumentException(bool isIllegal, string paramName = null)
        {
            if (isIllegal)
            {
                if (paramName == null)
                {
                    paramName = string.Empty;
                }
                Debug.Assert(false, paramName);
                throw new ArgumentException(string.Empty, paramName);
            }
        }

        [Conditional(Validator.DebugSymbal)]
        public static void ThrowInvalidOperationException(bool isIllegal, string message = null)
        {
            if (isIllegal)
            {
                if (message == null)
                {
                    message = string.Empty;
                }
                Debug.Assert(false, message);
                throw new InvalidOperationException(message);
            }
        }

        [Conditional(Validator.DebugSymbal)]
        public static void ThrowNotSupportedException(bool isIllegal, string message = null)
        {
            if (isIllegal)
            {
                if (message == null)
                {
                    message = string.Empty;
                }
                Debug.Assert(false, message);
                throw new NotSupportedException(message);
            }
        }

        [Conditional(Validator.DebugSymbal)]
        public static void ThrowException<T>(bool isIllegal, string environmentState) where T : Exception
        {
            if (isIllegal)
            {
                Debug.Assert(false, environmentState);
                try
                {
                    throw (T)Activator.CreateInstance(typeof(T), environmentState);
                }
                catch
                {
                    throw new InvalidOperationException(environmentState);
                }
            }
        }
        #endregion
    }
}
原文地址:https://www.cnblogs.com/Googler/p/2939138.html