标签: argument-validation

如果一个参数为null,最佳做法是什么?

在验证方法的输入时,我用来检查参数是否为null,如果是,我抛出一个ArgumentNullException.我为列表中的每个参数执行此操作,因此我最终得到如下代码:

 public User CreateUser(string userName, string password, 
                            string Email, string emailAlerts, 
                            string channelDescription)
    {

        if (string.IsNullOrEmpty(userName))
            throw new ArgumentNullException("Username can't be null");

        if (string.IsNullOrEmpty(Email))
            throw new ArgumentNullException("Email can't be null");
       //etc, etc, etc
    }
Run Code Online (Sandbox Code Playgroud)

这个可以吗?我为什么要这样做?如果我只是将所有检查分组并返回空值而不是抛出异常,那会没关系吗?解决这种情况的最佳做法是什么?

PS:我想改变这一点,因为使用长方法,这样做非常繁琐.
想法?

.net c# argument-validation

18
推荐指数
4
解决办法
4767
查看次数

C#:参数验证:null /空字符串

我不知道有多少次我不得不编写代码来验证字符串参数:

public RoomName(string name)
{
    if (string.IsNullOrEmpty(name))
    {
        throw new ArgumentException("Cannot be empty", "name");
    }
}
Run Code Online (Sandbox Code Playgroud)

反正有没有避免这个?是否有一些属性或设计合同机制来避免这种情况?有没有办法说:

public RoomName(NotNullOrEmptyString name)
{
Run Code Online (Sandbox Code Playgroud)

而不必实际创建该类型?

c# string argument-validation

17
推荐指数
2
解决办法
8365
查看次数

C#:在扩展方法中验证"this"参数的最佳实践

假设我有一个扩展方法

public static T TakeRandom<T>(this IEnumerable<T> e)
{
    ...
Run Code Online (Sandbox Code Playgroud)

要验证参数e,我应该:

A)if(e == null)抛出新的NullReferenceException()
B)if(e == null)抛出新的ArgumentNullException("e")
C)不检查e

什么是共识?

我的第一个想法是始终验证参数,因此抛出ArgumentNullException.然后,由于TakeRandom()成为e的方法,也许它应该是NullReferenceException.但是如果它是NullReferenceException,如果我尝试在TakeRandom()中使用e的成员,那么无论如何都会抛出NullReferenceException.

也许我应该使用Reflector达到峰值并找出框架的作用.

c# extension-methods exception argument-validation

6
推荐指数
1
解决办法
2722
查看次数

如何避免参数验证

验证原始参数和"复杂数据"

验证参数

在编写方法时,应在执行任何操作之前首先验证参数.例如,假设我们有一个代表人的类:

public class Person
{
    public readonly string Name;
    public readonly int Age;

    public class Person(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个Person类出了什么问题?在将值设置为Person字段之前,不验证名称和年龄."验证?"是什么意思?应该检查两个参数,它们的值是可接受的.例如,如果name的值是空字符串怎么办?或者年龄的值是-10?

通过在值不可接受时抛出ArgumentExceptions或派生异常来执行验证参数.例如:

public class Person(string name, int age)
{
    if (String.IsNullOrEmpty(name))
    {
        throw new ArgumentNullException
            ("name", "Cannot be null or empty.");
    }

    if (age <= 0 || age > 120)
    {
        throw new ArgumentOutOfRangeException
            ("age", "Must be greater than 0 and less than 120.");
    }

    this.Name = name;
    this.Age = …
Run Code Online (Sandbox Code Playgroud)

c# argument-validation

5
推荐指数
1
解决办法
439
查看次数