Passing a variable number of arguments

I need to write a function that takes a variable number of arguments. I read a little about the [] options, but I don't think this will work in my case. My function should take a variable number int, and then the corresponding bool value for each of them. I have to iterate over each of these combinations and enter them into the database. Just looking for someone to point me in the right direction. Thanks.

+5
source share
4 answers

I would recommend creating a structure and passing it as parameters. In my example, your structure is an estimate of some kind:

public struct RaceScore
{
     public bool FinishedRace;
     public int Points;
}

Your method signature will be as follows:

public void SaveScores(params RaceScore[] scores)

Here is an example of a call to SaveScores:

RaceScore score = new RaceScore() { FinishedRace = true, Points = 20 };
RaceScore score2 = new RaceScore() { FinishedRace = false, Points = 15 };
SaveScores(score, score2);
+16

params, params , int + bool. KeyValuePair<TKey,TValue> , .

, IEnumerable<T>, .

:

public void SaveValues(IEnumerable<KeyValuePair<int,bool>> values)
{
    foreach(var pair in values)
    {
        int intVal = pair.Key;
        bool boolVal = pair.Value;
        // Do something here...
    }
}

, ..

public void SaveValues(params KeyValuePair<int,bool>[] values)

, , . IEnumerable<T> , LINQ .. .

+11

- , . , int bool. :

public struct IntBoolStruct {
   public bool BoolValue;
   public int IntValue;
}

public void YourMethod( params IntBoolStruct[] values ) {}

EDIT: , , nullable int.

public void YourMethod( params int?[] values ) {}
+5

: - .

    class paramstest {
        private void _passALot(params Object[] values) {
            System.Console.WriteLine(" [foreach]");

           foreach (object o in values) {
                System.Console.Write(o.ToString() + ", ");
            }

            System.Console.WriteLine(System.Environment.NewLine + " [for]");

            for (int i = 0; i < values.Length; i += 2) {
                int? testval = values[i] as Int32?;
                bool? testbool = values[i + 1] as Boolean?;

                System.Console.WriteLine(String.Format("Int: {0}, Bool: {1}", testval, testbool));
            }
        }

        public void test() {
            _passALot(1, true, 2, false, 3, true, "q", false);
        }
    }

>

[foreach]
1, True, 2, False, 3, True, q, False,
 [for]
Int: 1, Bool: True
Int: 2, Bool: False
Int: 3, Bool: True
Int: , Bool: False

:)

0

All Articles