【问题标题】:Declaring an unknown Type in class declaration c#在类声明c#中声明一个未知类型
【发布时间】:2012-09-02 14:34:54
【问题描述】:

好吧,我不应该是第一个提出这个问题的人。但我还没有找到解决我的问题的方法。也许我只是不知道确切的术语。

我目前正在(用 c# 编写)一个必须处理不同类型游戏玩家的程序。

即:

public class Gamer {

  public int ID { set; get; }
  public string Name { set; get; }

public Gamer(int ID, string Name) 
{
  this.ID = ID;
  this.Name = Name;
}

然后我将区分具有不同属性的不同类型的玩家(例如国际象棋、围棋、高尔夫):

public class ChessPlayer : Gamer {

  public int ELORank { set; get; }

  public ChessPlayer(int ID, string Name, int ELORank) 
  {
    this.ID = ID;
    this.Name = Name;
    this.ELORANK = ELORank;
  }
}

public class TennisPlayer : Gamer {

  public int SinglesRank { set; get; }
  public int DoublesRank { set; get; }
  public bool LeftHanded { set; get; }

  public TennisPlayer(int ID, string Name,
                      int SinglesRank, int DoublesRank bool LeftHanded) 
  {
    this.ID = ID;
    this.Name = Name;
    this.SinglesRank = SinglesRank;
    this.DoublesRank = DoublesRank;
    this.LeftHanded = LeftHanded;
  }
}

然后我有一个静态类,我在其中编写当前参与的 Gamers:

public static class Game{
  public static int Type { set; get; } //0 = Chess, 1 = Tennis
  public static var Gamer { set; get; }
}

这样我就可以在ButtonClick上写了:

private void ButtonClick (Sender object, Event e)
{
  ArrayList Participants = new ArrayList;
  switch (Game.type)
  {
    case 0: //Chess
    {
      [...] //Add chess player to ArrayList
      break;
    Game.Gamer = Participants.ToArray(typeof(ChessPlayer)) as ChessPlayer[];
    }
    case 1: //Tennis
    {
      [...] //Add tennis player to ArrayList
      Game.Gamer = Participants.ToArray(typeof(TennisPlayer)) as TennisPlayer[];
      break;
    }

  }
}

我也想这样做,但是

public static var Gamer { set; get; }

只是不允许,因为你的类声明中不能有 var。

这就是我目前使用 AllGamer 类的原因,它具有 ChessPlayer 和 TennisPlayer 等的每个构造函数和属性。它正在工作。但我认为我最初的想法会更好。

我对 c# 很陌生,这是我的第一个真正的 OOP 项目。因此,如果您有任何想法,我真的很高兴听到/阅读它们。是否有可能使用未确定类型或在运行时确定类型(类似于“var”)?

【问题讨论】:

    标签: class types declaration var


    【解决方案1】:

    因为 ChessPlayer 和 TennisPlayer 都是 Gamer,所以可以创建 Gamer 类型的属性

     public Gamer TheGamer {get;set;}
    

    另一种方法是定义一个Interface,比如IGamer,并让您的玩家实现该接口

     public IGamer TheGamer {get;set;}
    

    【讨论】:

    • 但是 ELORank、左撇子、.. 不是 Gamer Game 的属性。TheGamer.ELORank 不起作用
    • 如果您知道它是 TennisPlayer,则将其转换为 TennisPlayer。
    • 非常感谢。从来没有想过这样的事情可以奏效。我想知道如果我正在分配一个玩家但在其中放置一个玩家和其他内容,内存分配是如何工作的......我认为我可以做类似的事情:TennisPlayer Foo = new Gamer(); 因为 TennisPlayer 有足够的内存供玩家使用......但不是Gamer Bar = new TennisPlayer();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多