C#错误消息:无法隐式转换类型

时间:2015-05-22 20:38:17

标签: c# class multidimensional-array

以下代码抛出以下异常:

  

错误1无法隐式转换类型   'Clarity.DevTest.Exercises.ChessPosition'来   “System.Collections.Generic.IEnumerable<   Clarity.DevTest.Exercises.ChessPosition>”。显式转换   存在(你是否错过演员表?)

有人可以向我解释出错的原因以及为什么它无法返回结果?

using System;
using System.Collections.Generic;

namespace Clarity.DevTest.Exercises
{
public class Exercise1
{
    public IEnumerable<ChessPosition> GetLegalMoves(ChessPosition rookToMove, ChessPosition friendlyRook, ChessPosition enemyRook1, ChessPosition enemyRook2)
    {

        //create array to hold positions
        ChessPosition[,] coords = new ChessPosition [8,8];
        //set the Rooks into the correct places on the array
        //eg rookToMove.X = 4, rookToMove.Y = 5, "R" would be places in 4,5
        coords[rookToMove.X, rookToMove.Y] = "R";
        coords[friendlyRook.X, friendlyRook.Y] = "F";
        coords[enemyRook1.X, enemyRook1.Y] = "1";
        coords[enemyRook2.X, enemyRook2.Y] = "2";

        //throw new NotImplementedException();

        ChessPosition result = new ChessPosition(4, 5);
        return result;
    }
}

public partial class ChessPosition
{
    public ChessPosition(int x, int y)
    {
        //check to see if out of bounds
        if (x < 1 || x > 8 || y < 1 || y > 8)
        {
            throw new ArgumentException("x and y must be in the range 1-8");
        }
        X = x;
        Y = y;
    }

    public int X { get; set; }
    public int Y { get; set; }
  }
}

3 个答案:

答案 0 :(得分:2)

您的方法表示它返回了IEnumerable<ChessPosition>,但实际上您返回ChessPosition

您的方法签名是:

public IEnumerable<ChessPosition> GetLegalMoves(...

因此,您告诉任何访问该方法的人,他们将收到ChessPosition

的集合

但你回来了:

ChessPosition result = new ChessPosition(4, 5);
return result;

这不是一个集合,而是一个ChessPosition

您需要确定您的方法是返回单个ChessPosition还是多个。

答案 1 :(得分:1)

您的方法的返回类型&#39; GetLegalMoves&#39;与您返回的内容不符 - 更改返回类型以删除不可数,因此它只是返回&#39; ChessPosition&#39;

答案 2 :(得分:1)

您返回单个ChessPosition而不是可枚举的结果集合。

返回一个可枚举的集合:

ChessPosition result = new ChessPosition(4, 5);
IEnumerable<ChessPosition> results = new List<ChessPosition>();
results.Add(result);

return results;

或更改您的退货类型:

public ChessPosition GetLegalMoves(
    ChessPosition rookToMove, ChessPosition friendlyRook, ChessPosition 
    enemyRook1, ChessPosition enemyRook2)