好吧,这可能是不可能的,但我想使用一个字符串作为函数的参数,并使用该字符串来命名一个新的类实例。使用Visual Studio 2010和C#XNA,我尝试使用谷歌和这里搜索解决方案,但也许我没有使用正确的关键字或其他东西。
public void createRace(string raceName, Element element1, Element element2, AbilityScore stat1, AbilityScore stat2, AbilityScore stat3, AbilityScore stat4)
{
Race temp = new Race();
temp.raceName = raceName;
temp.primaryElement = element1;
temp.secondaryElement = element2;
temp.primaryAbility = stat1;
temp.secondaryAbility1 = stat2;
temp.secondaryAbility2 = stat3;
temp.weakAbility = stat4;
}
我希望Race temp在命名Race的新实例时使用raceName而不是temp,如果不可能让我知道,我会找到一个解决方法。
答案 0 :(得分:1)
我会用字典来解决这个问题。以下代码将允许您基于“raceName”访问您的实例
Dictionary<string,Race> races = new Dictionary<string,Race>();
public void createRace(string raceName, Element element1, Element element2, AbilityScore stat1, AbilityScore stat2, AbilityScore stat3, AbilityScore stat4)
{
Race temp = new Race();
temp.raceName = raceName;
temp.primaryElement = element1;
temp.secondaryElement = element2;
temp.primaryAbility = stat1;
temp.secondaryAbility1 = stat2;
temp.secondaryAbility2 = stat3;
temp.weakAbility = stat4;
races.Add(raceName,temp);
}