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))
            
    {
            }

        }


  • 相关阅读:
    Zookeeper 基础知识【1】
    Spark 基础复习【1】
    ZooKeeper 入门 一致性
    Hive 视图 索引
    Yarn调度 历史与基础
    mysql 优化【1】
    TCP IP知识梳理
    Java 基础 锁
    Spark 累加器使用
    RATE-MAX----beta答辩博客
  • 原文地址:https://www.cnblogs.com/deerchao/p/1078826.html
Copyright © 2011-2022 走看看