c# 和/或 vb.net 等效于 apache commons 验证

本文关键字:apache commons 验证 net vb | 更新日期: 2023-09-27 17:55:19

在Java中,如果Apache Commons Lang jar在类路径中,我们可以做一行验证,比如

Validate.isTrue(someBoolean, "This should be true");

实际上,上述内容与

if (! someBoolean) {
    throw new RuntimeException("This should be true");
}

.net 世界中是否有可以做同样的事情?
我知道我在某处看到过类似事情的代码,但我不记得在哪里或系统税。

任何帮助都非常感谢。

c# 和/或 vb.net 等效于 apache commons 验证

当然,你可以自己写:

public static class Validate 
{
    public static void IsTrue(bool value) 
    {
        if (!value) throw new InvalidOperationException(message)
    }
}

此外,在 C# 或 VB 中,您可以使用代码协定:

Contract.Requires(someBoolean, "This should be true")

这需要从 Visual Studio 扩展站点下载代码协定扩展。您可以打开代码协定并在编译时对其进行验证,并且它允许指定相当任意的协定条件。