开发者

Trouble overloading methods when using string and string[]

开发者 https://www.devze.com 2022-12-21 15:43 出处:网络
I\'m having a little trouble overloading methods in C#.I have two methods that look like this. public static void Sample(string string1, string string2, string string3,

I'm having a little trouble overloading methods in C#. I have two methods that look like this.

public static void Sample(string string1, string string2, string string3, 
System.Windows.Forms.MessageBoxButtons buttons)
{}
public static void Sample(string string1, string[] string2, string string3, System.Windows.Forms.MessageB开发者_如何学GooxButtons buttons)
{}

When I try to call the second method I get an error "Cannot convert 'string[]' to 'string'". What am I doing wrong?

It works when I overload methods that do not take the MessageBoxButtons enumeration, but not for this method.

Calling code looks like this.

string[] myStringArray = new string[] {"this is a test","of overloaded methods"};
Sample("String1",myStringArray,"String2",System.Windows.Forms.MessageBoxButtons.OK);

Edit: The problem was in my build script. It was not waiting for the dll to be created before creating the next dll that referenced the first, so changes that where made where not in the dll that was being referenced.

Guess this is a pitfall of not using an IDE.


Still no errors when I compile this:

using System;

namespace Test
{
    class Program
    {
        public static void Sample(string string1, 
            string string2, 
            string string3, 
            System.Windows.Forms.MessageBoxButtons buttons)
        { }
        public static void Sample(string string1, 
            string[] string2, 
            string string3, 
            System.Windows.Forms.MessageBoxButtons buttons)
        { }

        static void Main()
        {
            string[] myStringArray = 
                new string[] { "this is a test", "of overloaded methods" };
            Sample("String1", 
                myStringArray, 
                "String2", 
                System.Windows.Forms.MessageBoxButtons.OK);
        }
   }
}

Does this error in your environment?


You haven't shown the calling code. My guess is that you're trying to pass in a string array as the first or third argument instead of the second - but if you post your code (or even better, a short but complete example) then we'll be able to sort it out.


Without seeing how you're calling this, it's hard to tell, but you'll need to ensure your first and third parameters are always string, and your last parameter, of course, is of the type MessageBoxButtons. Only the second parameter can change.


Could this serve your need?

public static void Sample(MessageBoxButtons buttons, params string[] args)
{
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号