如何在 C# WPF 中从多个 类 调用接口方法?
How to call interface method from multiple classes in c# WPF?
我正在尝试用 c# WPF 制作国际象棋游戏。我有多个 类,每种棋子都有一个,它们都实现相同的接口。所有 pieces 对象都存储在类型为 object[] 的二维数组中(感觉这不是正确的方法)。我想遍历此数组以通过调用 Board[x, y].ImgURI 绘制每个相应的图像,但我得到:
CS1061 'object' 不包含 'ImgURI' 的定义,并且找不到接受类型 'object' 的第一个参数的可访问扩展方法 'ImgURI'
class Rook : Igamepiece{...}
class King : Igamepiece{...}
class Queen : Igamepiece{...}
interface Igamepiece{
public string ImgURI { get; set; } //property that holds the image Uri
}
class Main{
public object[,] Board = new object[8, 8]; //array containing objects of different types
for (int y = 0; y < Board.GetLength(0); y++)
{
for (int x = 0; x < Board.GetLength(1); x++)
{
GameArea.Children.Add(new Image
{
Source = new BitmapImage(new Uri(Board[x, y].ImgURI, UriKind.Relative)),
Width = SquareSize,
Height = SquareSize,
Margin = new Thickness(nextX, nextY, 0, 0)
});
nextX += SquareSize;
}
nextX = 0;
nextY += SquareSize;
}
}
只需更改:
public object[,] Board = new object[8, 8];
至:
public Igamepiece[,] Board = new Igamepiece[8, 8];
我正在尝试用 c# WPF 制作国际象棋游戏。我有多个 类,每种棋子都有一个,它们都实现相同的接口。所有 pieces 对象都存储在类型为 object[] 的二维数组中(感觉这不是正确的方法)。我想遍历此数组以通过调用 Board[x, y].ImgURI 绘制每个相应的图像,但我得到:
CS1061 'object' 不包含 'ImgURI' 的定义,并且找不到接受类型 'object' 的第一个参数的可访问扩展方法 'ImgURI'
class Rook : Igamepiece{...}
class King : Igamepiece{...}
class Queen : Igamepiece{...}
interface Igamepiece{
public string ImgURI { get; set; } //property that holds the image Uri
}
class Main{
public object[,] Board = new object[8, 8]; //array containing objects of different types
for (int y = 0; y < Board.GetLength(0); y++)
{
for (int x = 0; x < Board.GetLength(1); x++)
{
GameArea.Children.Add(new Image
{
Source = new BitmapImage(new Uri(Board[x, y].ImgURI, UriKind.Relative)),
Width = SquareSize,
Height = SquareSize,
Margin = new Thickness(nextX, nextY, 0, 0)
});
nextX += SquareSize;
}
nextX = 0;
nextY += SquareSize;
}
}
只需更改:
public object[,] Board = new object[8, 8];
至:
public Igamepiece[,] Board = new Igamepiece[8, 8];