【问题标题】:Extension method on array can not be matched when using `ref` arguments使用`ref`参数时无法匹配数组上的扩展方法
【发布时间】:2013-08-01 21:27:14
【问题描述】:

以下是我正在使用的一些代码;它将方法添加到内置类型以查找数组中元素的索引(如果它在数组中)。 我遇到的问题是 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)
        {

        }
    }
}

【问题讨论】:

    标签: c# multidimensional-array extension-methods invalid-argument


    【解决方案1】:

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

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

    【讨论】:

    • +1。请注意,如果 OP 从方法(即 Tuple&lt;int,int&gt;Point 自定义类型)返回位置,而不是不寻常的 out/ref,则不需要此错误并强制用户指定 ref
    【解决方案2】:

    如果 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);
    }
    

    【讨论】:

      【解决方案3】:
      public static void IndexOf(this string[,] array, string find, ref int x, ref int y)
      

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

      感谢所有发布答案的人。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-06
        • 2023-01-11
        • 1970-01-01
        • 2014-03-25
        • 2016-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多