【问题标题】:Cannot implicitly convert type 'System.Array' to 'string[]' in windows form无法以 Windows 形式将类型“System.Array”隐式转换为“string[]”
【发布时间】:2013-03-04 00:26:39
【问题描述】:

我的 winforms app(c#) 中有一个函数 (function1),它返回一个数组

函数内部1

public array function1(string value)
{
string[] array = new string[12];
     //assigning values to the array elements....
retrun array;
}

我这样称呼这个函数

string id="Some id";
string[] array2 = new string[12];
array2=this.function1(id);

但它给了我错误

无法将类型“System.Array”隐式转换为“string[]”。存在显式转换(您是否缺少演员表?)

请高手帮帮我!

【问题讨论】:

  • 我什至无法理解它是怎么来的:错误 CS0246:找不到类型或命名空间名称“数组”。
  • 函数返回的“数组”可以是任意数组;但是 array2 只能保存对字符串数组的引用。因此错误。将函数的返回类型改为字符串[]。

标签: c# arrays


【解决方案1】:

改变

public array function1(string value)

public string[] function1(string value)

在您的使用示例中,您不需要事先将数组初始化为new string[12],因为您的函数无论如何都会返回一个新数组。

【讨论】:

    【解决方案2】:

    function1 的签名应该是public string[] function1(string value)。 返回类型arraystring[]类型的变量不匹配

    【讨论】:

      【解决方案3】:

      这可行,但不确定问题所在:

      public Form1()
      {
          InitializeComponent();
          string id = "Some id"; 
          string[] array2 = new string[12]; 
          array2 = this.function1(id);
      }
      
      public string[] function1(string value)
      {
          string[] array = new string[12];
          array[0] = value; // for example
          return array;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        • 1970-01-01
        相关资源
        最近更新 更多