.NET Guard Class Library?

后端 未结 6 1558
无人及你
无人及你 2020-12-13 15:00

I\'m looking for a library or source code that provides guard methods such as checking for null arguments. Obviously this is rather simple to build, but I\'m wondering if th

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 15:50

    There is CuttingEdge.Conditions. Usage example from the page:

    public ICollection GetData(Nullable id, string xml, ICollection col)
    {
        // Check all preconditions:
        id.Requires("id")
            .IsNotNull()          // throws ArgumentNullException on failure
            .IsInRange(1, 999)    // ArgumentOutOfRangeException on failure
            .IsNotEqualTo(128);   // throws ArgumentException on failure
    
        xml.Requires("xml")
            .StartsWith("") // throws ArgumentException on failure
            .EndsWith(""); // throws ArgumentException on failure
    
        col.Requires("col")
            .IsNotNull()          // throws ArgumentNullException on failure
            .IsEmpty();           // throws ArgumentException on failure
    
        // Do some work
    
        // Example: Call a method that should not return null
        object result = BuildResults(xml, col);
    
        // Check all postconditions:
        result.Ensures("result")
            .IsOfType(typeof(ICollection)); // throws PostconditionException on failure
    
        return (ICollection)result;
    }
    

    Another nice approach, which isn't packaged in a library, but could easily be, on Paint.Net blog:

    public static void Copy(T[] dst, long dstOffset, T[] src, long srcOffset, long length)
    {
        Validate.Begin()
                .IsNotNull(dst, "dst")
                .IsNotNull(src, "src")
                .Check()
                .IsPositive(length)
                .IsIndexInRange(dst, dstOffset, "dstOffset")
                .IsIndexInRange(dst, dstOffset + length, "dstOffset + length")
                .IsIndexInRange(src, srcOffset, "srcOffset")
                .IsIndexInRange(src, srcOffset + length, "srcOffset + length")
                .Check();
    
        for (int di = dstOffset; di < dstOffset + length; ++di)
            dst[di] = src[di - dstOffset + srcOffset];
    }
    

    I use it in my project and you could borrow the code from there.

提交回复
热议问题