zoukankan      html  css  js  c++  java
  • A new way to perform parameter validation in C# 3.0

    首先看用法:
        class Program
        
    {
            
    static void Main(string[] args)
            
    {
                
    string param = null;
                
    try
                
    {
                    DoSomething(param);
                }

                
    catch (ContractException ex)
                
    {
                    Console.WriteLine(
    "Exception: {0}", ex.Message);
                }

                Console.ReadKey();
            }


            
    private static void DoSomething(string param)
            
    {
                Contract.Requires(x 
    => param != null);
                Console.WriteLine(
    "after validating parameters..");
            }

        }


    运行结果是:
    Exception: Contract broken: x => (value(CSharpByContract.Program+<>c__DisplayCla
    ss0).param 
    != null)

    加粗的部分显示了参数验证失败的原因.需要注意的是,我们在验证时并不用手写"param!=null"这样的字符串,节省了时间,也减少了不一致.

    代码:
        public static class Contract
        
    {
            
    /// <summary>
            
    /// lazy programer's assert that gives a meaningful contract broken message
            
    /// </summary>
            
    /// <param name="condition">a bool expression to assert to be true</param>

            public static void Requires(Expression<Func<objectbool>> condition)
            
    {
                var x 
    = condition.Compile();
                
    if (!x(null))
                    
    throw new ContractException(condition.ToString());
            }

        }

        public class ContractException : ApplicationException
        
    {
            
    public ContractException(string message)
                : 
    base(string.Format("Contract broken: {0}", message))
            
    {
            }

        }


  • 相关阅读:
    Xshell 使用纪要
    矩阵求逆
    Ubuntu 增加新用户
    matlab 常用图像处理
    Surface Evolver 基本操作、使用指南和珍贵资料
    latex 裁剪图片
    Inkscape 输入希腊字母
    Pyton——int内部功能介绍
    python——登陆接口设计(循环方法)
    Python之三层菜单
  • 原文地址:https://www.cnblogs.com/deerchao/p/1078826.html
Copyright © 2011-2022 走看看