9

在查看Shrinkr的源代码时(我们都查看其他项目的源代码来学习,对吗??? :))我注意到以下 kewl 代码..(由我缩写,如下)

public virtual Foo Foo
{
    get;
    set 
    {
        Check.Argument.IsNotNull(value, "value"); 
        // then do something.
    }
}

注意到他们检查参数的流畅方式了吗?好的 :)

替代文字
(来源:cherrythian.com

所以..检查代码,他们有一些自定义类可以做到这一点......

public static class Check
{
    public static class Argument
    {
        public static void IsNotNull(object parameter, 
                                     string parameterName)
        { ... }

        public static void IsNotNullOrEmpty(string parameter, 
                                            string parameterName)
        { ... }

 .... etc ....
}

有没有通用的框架?

宝石安装 netFluentCheck

:)

4

5 回答 5

6

我最终使用了在 Codeplex 上找到的CuttingEdge Conditions

例如。

// Check all preconditions:
Condition.Requires(id, "id")
    .IsNotNull()          // throws ArgumentNullException on failure
    .IsInRange(1, 999)    // ArgumentOutOfRangeException on failure
    .IsNotEqualTo(128);   // throws ArgumentException on failure

好的 :)

于 2010-09-02T00:08:03.207 回答
2

试试FluentValidation

.NET 2.0 的 FluentValidation

于 2010-09-01T16:01:30.693 回答
1

这是我不久前写的只有几行的简单类(来自这里:http ://code.google.com/p/hotwire-queue/wiki/QuickAssert ),它执行类似于流利验证的操作,使用了稍微不同的风格,我觉得更容易阅读(ymmv)。不需要任何第三方库,如果验证失败,您会收到一条简单的错误消息,其中包含失败的确切代码。

config.Active.Should().BeTrue();
config.RootServiceName.Should().Be("test-animals");
config.MethodValidation.Should().Be(MethodValidation.afterUriValidation);
var endpoints = config.Endpoints;
endpoints.Should().NotBeNull().And.HaveCount(2);

对此:

config.Ensure(c => c.Active,
              c => c.RootServiceName == "test-animals",
              c => c.MethodValidation == MethodValidation.afterUriValidation,
              c => c.Endpoints != null && c.Endpoints.Count() == 2);

这是课程,希望它对某人有所帮助;-D

using System;
using System.Linq.Expressions;
using NUnit.Framework;

namespace Icodeon.Hotwire.Tests.Framework
{
    public static class QuickAssert
    {
        public static void Ensure<TSource>(this TSource source, params Expression<Func<TSource, bool>>[] actions)
        {
            foreach (var expression in actions)
            {
                Ensure(source,expression);
            }
        }

        public static void Ensure<TSource>(this TSource source, Expression<Func<TSource, bool>> action)
        {
            var propertyCaller = action.Compile();
            bool result = propertyCaller(source);
            if (result) return;
            Assert.Fail("Property check failed -> " + action.ToString());
        }
    }
}

在我编写 Ensure 时,Visual Studio 2010 不支持代码合同,但现在支持,请参阅http://msdn.microsoft.com/en-us/magazine/hh148151.aspx

于 2013-01-04T11:26:30.653 回答
1

是使用表达式的一个。由于这很简单,每个人似乎都有自己的实现......

于 2010-08-03T02:21:57.027 回答
1

您可以尝试Bytes2you.Validation ( Project )。它是快速、可扩展、直观且易于使用的 C# 库,为参数验证提供流畅的 API。提供在 .NET 应用程序中实现防御性编程所需的一切。

于 2014-11-17T21:32:31.057 回答