我在VS 2013中为Win Phone 8编程。
我有一个包含2个Observable Collections的游戏类:
public class Games
{
public Games() { }
public ObservableCollection<Game1> Games1 { get; set; }
public ObservableCollection<Game2> Games2 { get; set; }
}
第一场比赛和第二场比赛:
public class Game1: GameBase<PersonG1>
{
public Game1(){}
public string Game1Property{ get; set; }
}
public class Game2: GameBase<PersonG2>
{
public Game2(){}
public string Game2Property{ get; set; }
}
GameBaseClass:
public abstract class GameBase<TPerson> where TPerson : Person
{
public string GameStatus { get; set; }
public string GameDuration { get; set; }
public ObservableCollection<TPerson> Persons { get; set; }
}
人员类:
public class Person
{
public string Name { get; set; }
}
public class PersonG1: Person
{
public string PersonG1Property{ get; set; }
}
public class PersonG2: Person
{
public string Person2Property{ get; set; }
}
启动电话应用程序后,我将选择一个游戏,然后转到一个xaml页面,其中DataContext = Game1或Game2
但是我有一个页面:MakePerson.xaml,这个页面不知道DataContext或其他什么,我用它来为每个游戏添加人员,并且会为所有游戏使用相同的MakePerson.xaml,我转到Makeperson.xaml页面如下:
NavigationService.Navigate(new Uri(GlobalResources.MakePersonPage + "?index=" + _gameIndex.ToString() + "&pId=-1&gametype=Game1", UriKind.Relative));
其中_gameIndex表示ObservableCollection中游戏的索引,pID表示ObservableCollection人员中的personIndex,gt表示游戏类型,到达Makeperson.xaml页面我执行:
private object currGame;
private Person currPerson;
DataContext = currentPerson;
_gameIndex = int.Parse(NavigationContext.QueryString["index"]);
_personIndex = int.Parse(NavigationContext.QueryString["pId"]);
_gameType = NavigationContext.QueryString["gametype"];
switch (_gameType)
{
case "Game1":
{
currGame = Games.Games1[gameIndex];
currPerson = Games1[gameindex].Persons.ElementAt(personindex);
}
case "Game2":
currGame = Games.Games2[gameIndex]
currPerson = Games2[gameindex].Persons.ElementAt(personindex);
}
如何更改此结构,以便在makePerson.xaml中更舒适?我想通用接口?
我如何改变我的类,所以我总是有相同的对象,例如,或许像这样:
switch (_gameType)
{
case "Game1":
IGame currGame = Games.Game1s[_gameIndex];
currentPerson = currGame.Persons.ElementAt(persondindex);
break;
case "Game2":
IGame currGame = Games.Games2[_gameIndex];
currentPerson = currGame.Persons.ElementAt(persondindex);
break;
default:
break;
}
或我可以使用的其他解决方案?
谢谢。 (对不起英语不好)
答案 0 :(得分:0)
您的游戏已经从GameBase继承,因此您应该能够使用正常的多态性。因此,不是你的currGame是“对象”类型,它可以是“GameBase”类型。
GameBase currGame;
switch (_gameType)
{
case "Game1":
currGame = Games.Game1s[_gameIndex];
currentPerson = currGame.Persons.ElementAt(persondindex);
break;
case "Game2":
currGame = Games.Games2[_gameIndex];
currentPerson = currGame.Persons.ElementAt(persondindex);
break;
default:
break;
}
编辑: 您不希望强制转换为接口,因为它是多余的。 但您可以将GameBase更改为:
public abstract class GameBase
{
public string GameStatus { get; set; }
public string GameDuration { get; set; }
public ObservableCollection<Person> Persons { get; set; }
}