What is the smoothest, most appealing syntax you've found for asserting parameter correctness in c#?

后端 未结 14 1943
一个人的身影
一个人的身影 2020-12-22 23:50

A common problem in any language is to assert that parameters sent in to a method meet your requirements, and if they don\'t, to send nice, informative error messages. This

14条回答
  •  太阳男子
    2020-12-23 00:29

    Wow, I found something really interesting here. Chris above gave a link to another Stack Overflow question. One of the answers there pointed to a blog post which describes how to get code like this:

    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'm not convinced it is the best answer yet, but it certainly is interesting. Here's the blog post, from Rick Brewster.

提交回复
热议问题