gpt4 book ai didi

C# 错误消息 : Cannot Implicitly convert type

转载 作者:太空宇宙 更新时间:2023-11-03 19:59:03 25 4
gpt4 key购买 nike

下面的代码抛出以下异常:

Error 1 Cannot implicitly convert type 'Clarity.DevTest.Exercises.ChessPosition' to 'System.Collections.Generic.IEnumerable< Clarity.DevTest.Exercises.ChessPosition>'. An explicit conversion exists (are you missing a cast?)

谁能给我解释一下出了什么问题,为什么不能返回结果?

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; }
}
}

最佳答案

您将返回单个 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)

关于C# 错误消息 : Cannot Implicitly convert type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com