質問

I currently got something like this

public string MyFunction()
{
   return MyFunction(null);
}
public string MyFunction(short? variable)
{
   do something if null
   else do something else
   return string;
}

Now I'm trying to make something like

public string MyFunction(short[] variable)
{
   string a;
   foreach(var z in variable)
   a = a +" "+ MyFunction(z);
}

but i recive error

The call is ambiguous between the following methods or properties

Is it even possible to stay with only one parameter cause I know that makin' function with two params will resolve problem but still I will be using only one param. It's also impossible to replace null with chosen number (e.g. 0).

役に立ちましたか?

解決

You can use a cast to resolve the ambiguity:

return MyFunction((short?)null);

Without the cast there is no way for the compiler to detect which function you want to invoke.

他のヒント

Quick idea: Why not combine them using a variable length argument? This way you can call the same method in both cases, and let it call itself recursively for the items in the array:

    public string MyFunction(params short[] variables)
    {
        // edit: Added null-handling:
        if (variables == null)
        {
            return "<empty>";
        }

        string myString = string.Empty;
        if (variables.Length == 1)
        {
            // logic to handle the single variable
            return myString + variables[0];
        }
        else
        {
            foreach (var z in variables)
            {
                myString += " " + MyFunction(z);
            }
        }

        return myString;
    }

An example passing in to versions: Several short values, and an array. Both work fine:

class Program
{
    static void Main(string[] args)
    {
        var instance = new ClassContainingTheMethod();

        var res1 = instance.MyFunction(1, 2, 3);
        var res2 = instance.MyFunction(new short[]{4, 5, 6});

        Console.WriteLine(res1);
        Console.WriteLine(res2);
        Console.ReadKey();
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top