문제

Following is some code I'm working with; it adds methods to built-in types to find the index of an element in an array if it is in the array. The problem I'm having is that the code for the char[].IndexOf method works but my new code for the string[,] is not.

string[,].IndexOf(string from variable, int x,int y);

Displays an Error : The best overloaded method match for 'System.Array.IndexOf(int[], int, int)' has some invalid arguments Argument 1: cannot convert from 'string' to 'int[]'

I don't understand what the problem is. I have defined the method to take a string not an integer array, and the type does not have an IndexOf function built-in.

Code Excerpt: (Not exact code hopefully just what matters)

Using Extensions;

namespace one
{
    class Form
    private static char[] Alp = {'s','f'};

    private method1
    {
         int pos = Alp.IndexOf(char[x]);
    }

    private method2
    {
          string[,] theory = table of letters

          theory.IndexOf(string_array[0], x, y);
    }

namespace Extensions
{
    public static class MyExtensions
    {
        //Add method IndexOf to builtin type char[] taking parameter char thing
        public static int IndexOf(this char[] array, char thing)
        {
            for (int x = 0; x < array.Length; x++)
            {
                char element = array[x];
                if (thing == element) { return x; }
            }
            return -1;
        }

        public static void IndexOf(this string[,] array, string find, ref int x, ref int y)
        {

        }
    }
}
도움이 되었습니까?

해결책

Didn't you forget ref in your method call?

theory.IndexOf(string_array[0], ref x, ref y);

다른 팁

If x and y are set by your IndexOf method, you should use out instead of ref.

public static void IndexOf(this string[,] arr, string find, out int x, out int y)
{

}

// Then, you need to specify 'out' at the call site
theory.IndexOf(string_array[0], out x, out y);

You can use a Tuple to avoid having out parameters:

public static Tuple<int, int> IndexOf(this string[,] array, string find)
{
    // Logic here
    return new Tuple(x, y);
}
public static void IndexOf(this string[,] array, string find, ref int x, ref int y)

It turns out because x and y are requested by reference they also have to be called with the ref keyword. Why the error said the first parameter was wrong has got me.

Thanks to all of you who posted answers.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top