Tag: 参数validation

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

在validation方法的输入时,我曾经检查参数是否为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 } 这个可以吗? 我为什么要这样做? 如果我只是将所有检查分组并返回空值而不是抛出exception,那会没关系吗? 解决这种情况的最佳做法是什么? PS:我想改变这个,因为使用长方法,这样做非常繁琐。 想法?

C#:在扩展方法中validation“this”参数的最佳实践

假设我有一个扩展方法 public static T TakeRandom(this IEnumerable e) { … 要validation参数e,我应该: A)if(e == null)抛出新的NullReferenceException() B)if(e == null)抛出新的ArgumentNullException(“e”) C)不检查e 什么是共识? 我的第一个想法是始终validation参数,因此抛出ArgumentNullException。 然后,由于TakeRandom()成为e的方法,也许它应该是NullReferenceException。 但是如果它是NullReferenceException,如果我尝试在TakeRandom()中使用e的成员,那么无论如何都会抛出NullReferenceException。 也许我应该使用Reflector达到峰值并找出框架的作用。