嘿,我正在做一个人们可以打一点战争的项目。
现在我有了一个创建播放器的类,每次我将一个属性分配给我的类时,它都保持为空。这是我的代码,我已经评论了哪一个保持为空并且不知道为什么。您将看到的第一个代码是创建新播放器的方法,第三段代码是我的带有字符串的数组
public List<Speler> BeginSpel()
{
List<Speler> Spelers = new List<Speler>();
Random r = new Random();
for (int i = 1; i <= 20; i++)
{
Guid g;
g = Guid.NewGuid();
int rangindex = r.Next(0, 22);
int wapenindex = r.Next(0, 4);
DateTime vandaag = DateTime.Now;
//Wapen wapen = new Wapen();
string wapen = "";
switch (wapenindex)
{
case 0:
wapen = Wapen.mes.ToString();
break;
case 1:
wapen = Wapen.handgeweer.ToString();
break;
case 2:
wapen = Wapen.sniper.ToString();
break;
case 3:
wapen = Wapen.bazooka.ToString();
break;
}
//so the string below here always gets filled up but when i check my list the property where i use rangAfkorting just stays null
string rangAfkorting = Rang.rangAfkorting[rangindex];
Spelers.Add(new Speler(g.ToString(), "Player_" + i.ToString(), Rang.rang[rangindex], rangAfkorting, 100, wapen, vandaag.ToString(), "nog niet"));
}
return Spelers;
}
public class Speler
{
public string Naam { get; set; }
public string Id { get; set; }
public string Rang { get; set; }
public string Wapen { get; set; }
public string Aangemaakt { get; set; }
public string Rangafkorting { get; set; }
public string KIA { get; set; }
public int Health { get; set; }
public Speler(int health)
{
Health = health;
}
public Speler()
{
}
//rang afkorting stays null
public Speler(string id, string naam, string rang, string rangafkorting, int health, string wapen , string aangemaakt, string kia)
{
Naam = naam;
Id = id;
Rang = rang;
Health = health;
Wapen = wapen;
Aangemaakt = aangemaakt;
KIA = kia;
rangafkorting = Rangafkorting;
}
}
public static string[] rang = new string[] {"generaal",
"luitenant-generaal",
"generaal-majoor",
"brigade-generaal",
"kolonel",
"luitenant-kolonel",
"majoor",
"kapitein-commandant",
"kapitein",
"luitenant",
"onderluitenant",
"adjudant-majoor",
"adjudant-chef",
"adjudant",
"eerste sergeant-majoor",
"eerste sergeant-chef",
"eerste sergeant",
"sergeant",
"eerste korporaal-chef",
"korporaal-chef",
"korporaal",
"eerste soldaat",
"soldaat"};
public static string[] rangAfkorting = new string[]
{"Gen",
"LtGen",
"GenMaj",
"BdeGen",
"Kol",
"LtKol",
"Maj", "Cdt", "Kapt", "Lt", "OLt", "AdjtMaj", "AdjtChef", "Adjt", "1SgtMaj", "1SgtChef", "1Sgt", "Sgt", "1KplChef", "KplChef", "Kpl", "1Sdt", "Sdt"};
答案 0 :(得分:1)
问题出在您的Speler
构造函数中,您在其中进行Rangafkorting
的赋值。您试图为传递给构造函数的参数分配一个新值,而不是根据该参数设置类的属性。
请尝试以下操作(切换顺序):
Rangafkorting = rangafkorting;