Is there a way to distingish myFunc(1, 2, 3) from myFunc(new int[] { 1, 2, 3 })?

后端 未结 6 1633
暖寄归人
暖寄归人 2020-12-11 03:08

A question to all of you C# wizards. I have a method, call it myFunc, and it takes variable length/type argument lists. The argument signature of myFunc itself is my

6条回答
  •  不知归路
    2020-12-11 04:02

    Yes, you can, checking the params length and checking the argument type, see the following working code sample:

    class Program
    {
        static void Main(string[] args)
        {
            myFunc(1, 2, 3);
            myFunc(new int[] { 1, 2, 3 });
        }
    
        static void myFunc(params object[] args)
        {
            if (args.Length == 1 && (args[0] is int[]))
            {
                // called using myFunc(new int[] { 1, 2, 3 });
            }
            else
            {
                //called using myFunc(1, 2, 3), or other
            }
        }
    }
    

提交回复
热议问题