【问题标题】:How to call interface method from multiple classes in c# WPF? [duplicate]如何从 c# WPF 中的多个类调用接口方法? [复制]
【发布时间】:2020-11-13 11:06:32
【问题描述】:

我正在尝试在 c# WPF 中制作国际象棋游戏。我有多个类,每种棋子都有一个类,它们都实现了相同的接口。所有的片断对象都存储在一个 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;
        }
 }           

 

【问题讨论】:

  • 当你创建一个类型对象的集合时,你很有可能在做一些可疑的事情。

标签: c# wpf interface


【解决方案1】:

只是改变:

public object[,] Board = new object[8, 8]; 

到:

public Igamepiece[,] Board = new Igamepiece[8, 8]; 

【讨论】:

    猜你喜欢
    • 2013-11-29
    • 2013-01-26
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2014-09-26
    • 2014-06-26
    相关资源
    最近更新 更多