0

以下是我正在使用的一些代码;它向内置类型添加方法以查找数组中元素的索引(如果它在数组中)。我遇到的问题是 char[].IndexOf 方法的代码有效,但我的 string[,] 新代码无效。

string[,].IndexOf(来自变量的字符串, int x,int y);

显示错误:'System.Array.IndexOf(int[], int, int)' 的最佳重载方法匹配有一些无效参数 参数 1:无法从 'string' 转换为 'int[]'

我不明白问题是什么。我已经定义了获取字符串而不是整数数组的方法,并且该类型没有内置的 IndexOf 函数。

代码摘录:(不确切的代码希望只是重要的)

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)
        {

        }
    }
}
4

3 回答 3

2

你没有忘记ref你的方法调用吗?

theory.IndexOf(string_array[0], ref x, ref y);
于 2013-08-01T21:32:33.290 回答
1

如果 x 和 y 由 IndexOf 方法设置,则应使用 out 而不是 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);

您可以使用元组来避免没有参数:

public static Tuple<int, int> IndexOf(this string[,] array, string find)
{
    // Logic here
    return new Tuple(x, y);
}
于 2013-08-01T23:11:10.127 回答
0
public static void IndexOf(this string[,] array, string find, ref int x, ref int y)

事实证明,因为 x 和 y 是通过引用请求的,所以它们也必须使用 ref 关键字来调用。为什么错误说第一个参数错误让我明白了。

感谢所有发布答案的人。

于 2013-08-02T00:01:44.833 回答