c# -使用foreach循环遍历方法参数

本文关键字:遍历 方法 参数 循环 foreach 使用 | 更新日期: 2023-09-27 18:03:11

是否可以通过函数参数循环检查它们是否为null(或通过另一个自定义函数检查它们)?像这样:

public void test (string arg1, string arg2, object arg3, DataTable arg4)
{
    foreach (var item in argus)
        {
            if( item == null)
             {
                throw;
             }
        }
   // do the rest...
}

"argus"的正确关键字是什么?我知道这是可能的一些更多的if语句,但寻找一个更快的方式…

c# -使用foreach循环遍历方法参数

您可以使用params关键字来遍历所有参数,但随后您将在方法本身中使用它们的类型。我会写一个实用函数来检查null

public void CheckForNullArguments(params object[] args)
{
    foreach (object arg in args)
       if (arg == null) throw new ArgumentNullException();
}

你可以像

一样在方法的开头调用它
CheckForNullArguments(arg1, arg2, arg3, arg4);

我想你不想在项目中更改每个方法的参数。你可以使用PostSharp,但也有其他方法,这取决于你的框架。

using System;
using System.Data;
using System.Reflection;
using PostSharp.Aspects;
namespace TestAOP
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeClass someInstance = new SomeClass();
            someInstance.test(null, null, null, null);
        }
    }

    public class SomeClass
    {
        [CheckForNulls]
        public void test(string arg1, string arg2, object arg3, DataTable arg4)
        {           
            // do the rest...
        }
    }
    [Serializable]
    public class CheckForNullsAttribute : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            ParameterInfo[] parameters = args.Method.GetParameters();            
            for (int i = 0; i < args.Arguments.Count; i++)
            {
                if (args.Arguments[i] == null)
                    throw new ArgumentNullException(parameters[i].Name);
            }
        }
    }
}

http://www.sharpcrafters.com/获取PostSharp,也可以在那里找到doc。

如果您想要简单地遍历参数,您应该考虑使用params关键字

public void test (params object args[])
{
    foreach(var argument in args)
    {
        if(item == null)
        {
            throw new ArgumentNullException();
        }
    }
}

除此之外,你可以使用反射,但似乎你不太需要它

LINQ方式:

public static void Test(params object[] args)
{
    if (args.Any(a => a == null))
    {
        throw new ArgumentNullException("args");
    }
}