A new way to perform parameter validation in C# 3.0
首先看用法:
运行结果是:
加粗的部分显示了参数验证失败的原因.需要注意的是,我们在验证时并不用手写"param!=null"这样的字符串,节省了时间,也减少了不一致.
代码:
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..");
}
}
{
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)
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<object, bool>> condition)
{
var x = condition.Compile();
if (!x(null))
throw new ContractException(condition.ToString());
}
}
{
/// <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<object, bool>> 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))
{
}
}
{
public ContractException(string message)
: base(string.Format("Contract broken: {0}", message))
{
}
}