C# check if you have passed arguments or not

前端 未结 6 921
灰色年华
灰色年华 2020-12-29 02:36

I have this code:

public static void Main(string[] args)
{         
    if (string.IsNullOrEmpty(args[0]))  // Warning : Index was out of the bounds of the a         


        
6条回答
  •  清酒与你
    2020-12-29 03:07

    it's an array and there's two scenarios that might have the meaning NO arguments passed. Depending on your semantics

    args == null or args.Length == 0

    In this case where the method is called when the program is executed (e.g. not calling the method as part of say a unit test) the args argument will never be null (making the first test redundant) I've included it for completeness because the same situation might easily be encountered in other methods than main

    if you test them in that order you don't have to worry about args being null in the latter expression

    if(args == null || args.Length == 0){
        ComputeNoParam cptern = new ComputeNoParam();
        cptern.ComputeWithoutParameters();
    }
    else
    {
        ComputeParam cpter = new ComputeParam();
        foreach (string s in args){...}
    }
    

提交回复
热议问题