代码之家  ›  专栏  ›  技术社区  ›  AndrewC

对方法参数执行检查的更快方法

  •  2
  • AndrewC  · 技术社区  · 14 年前

    我有这样的方法:

    public void MyMethod(string arg1, string arg2, int arg3, string arg4, MyClass arg5)
    {
        // some magic here
    }
    

    参数都不能为null,字符串参数也不能等于 String.Empty

    而不是我有一大堆:

    if(arg1 == string.Empty || arg1 == null)
    {
        throw new ArgumentException("issue with arg1");
    }
    

    有没有更快的方法检查所有的字符串参数?

    如果我的问题不清楚,我道歉。

    7 回复  |  直到 14 年前
        1
  •  7
  •   Andrew Bezzub    14 年前

    您可以创建或使用框架来检查方法的契约,例如。 Code Contracts .

    您还可以创建各种实用程序方法,如 ThrowIfNullOrEmpty 谁将封装检查参数的逻辑。

        2
  •  4
  •   driis    14 年前

    if (String.IsNullOrEmpty(arg1) )
        throw new ArgumentException("issue with arg1");
    

    如果您使用的是framework4,那么还有一个 String.IsNullOrWhiteSpace 方法(如果有人使用仅包含空格的字符串调用该方法,您可能还希望抛出)。

    Code Contracts -但是使用它的语法仍然是一个方法调用。

        3
  •  3
  •   Darin Dimitrov    14 年前
    if (string.IsNullOrEmpty(arg1))
    {
        throw new ArgumentException("issue with arg1");
    }
    

    code contracts 在.NET 4中。

        4
  •  3
  •   Reed Copsey    14 年前

    CuttingEdge.Conditions 提供了一个流畅的界面:

    public void MyMethod(string arg1, string arg2, int arg3, string arg4, MyClass arg5)
    {
        Condition.Requires(arg1, "arg1").IsNotNull().IsNotEmpty().StartsWith("Foo");
    }
    

        5
  •  3
  •   Hans Passant    7 年前

    框架中这种模式的典型示例是Process类。ProcessStartInfo帮助程序类使其保持可用。

        6
  •  0
  •   dthorpe    14 年前

    首先,你可以用 if (!String.IsNullOrEmpty(arg1)) 减少if表达式。

    Debug.Assert(!String.IsNullOrEmpty(arg1), "msg"); 等等。断言从发布版本中剥离出来。

    第三,退房 DevLabs: Code Contracts

        7
  •  -1
  •   abatishchev Karl Johan    14 年前

    就我所能理解的问题而言,那又如何呢:

    static void Main(string[] args)
    {
        Test(null, "", "", "");
    }
    
    static void Test(MyClass arg1, params string[] args)
    {
        if (args.Count(a => String.IsNullOrEmpty(a)) == args.Length)
        {
            throw new Exception("All params are null or empty");
        }
    }