【发布时间】: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