遍历方法的参数以进行验证 [英] Iterate through method's parameters for validation purposes
问题描述
我一直认为,能够执行此类操作会很有用,例如,检查参数是否为空引用并最终引发异常.
这样可以节省一些键入时间,并且也将使您无法忘记添加检查是否添加了新参数.
I've been thinking that it would be useful to be able to do such a thing, for example, to check the parameters for null references and eventually throw an exception.
This would save some typing and also would make it impossible to forget to add a check if a new parameter is added.
推荐答案
好吧,除非您计数:
public void Foo(string x, object y, Stream z, int a)
{
CheckNotNull(x, y, z);
...
}
public static void CheckNotNull(params object[] values)
{
foreach (object x in values)
{
if (x == null)
{
throw new ArgumentNullException();
}
}
}
为避免数组创建失败,对于不同数量的参数,您可能会有很多重载:
To avoid the array creation hit, you could have a number of overloads for different numbers of arguments:
public static void CheckNotNull(object x, object y)
{
if (x == null || y == null)
{
throw new ArgumentNullException();
}
}
// etc
一种替代方法是使用属性声明参数不应为null,然后将 PostSharp 设置为生成适当的检查:
An alternative would be to use attributes to declare that parameters shouldn't be null, and get PostSharp to generate the appropriate checks:
public void Foo([NotNull] string x, [NotNull] object y,
[NotNull] Stream z, int a)
{
// PostSharp would inject the code here.
}
诚然,我可能希望PostSharp将其转换为代码合同调用,但是我不愿意知道两个人在一起玩得如何.也许一天,我们就能写出类似Spec#的代码:
Admittedly I'd probably want PostSharp to convert it into Code Contracts calls, but I don't know how well the two play together. Maybe one day we'll be able to write the Spec#-like:
public void Foo(string! x, object! y, Stream! z, int a)
{
// Compiler would generate Code Contracts calls here
}
...但在不久的将来不会:)
... but not in the near future :)
这篇关于遍历方法的参数以进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!