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

    }


posted on 2008-02-23 16:27  deerchao  阅读(438)  评论(0编辑  收藏  举报