是否有可能遍历C#方法的参数?有可能、遍历、参数、方法

2023-09-04 01:14:08 作者:罂花°雨

我一直在想,这将是能够做这样的事情,例如检查参数的空引用,并最终引发异常有用的。 这将节省一些打字,也将使它无法忘记添加一个检查,如果新的参数被添加。

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

另一种方法是使用属性来声明参数不能为空,并获得 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将其转换成 code合同电话,但我不知道该怎么还有两人一起玩。也许一个的一天,我们就可以写出规格#样:

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 :)