我一直在尝试找出是否有更好的方法来初始化我在此代码片段中使用的字符串数组。我想知道是否有一个函数,或者也许使用new
它会使代码中所有空字符串的调用和分配变得不必要。所以我可以在创建数组的同时初始化它们。
foreach (var unit in unitList)
{
//Sort units by each army
string unitName = unit.UnitName;
armyUnits.Add(unitName, unit);
//Sort unit properties by unit
List<string> properites = new List<string>();
string composition ="";
string weaponSkill ="";
string ballisticSkill ="";
string strength ="";
string initiative ="";
string toughness ="";
string wounds ="";
string attacks ="";
string leadership ="";
string savingThrow ="";
string specialRules ="";
string dedicatedTransport ="";
string options ="";
string armour ="";
string weapons ="";
properites.AddRange(new string[15]{
composition = unit.Composition,
weaponSkill = unit.WeaponSkill,
ballisticSkill = unit.BallisticSkill,
strength = unit.Strength,
initiative = unit.Initiative,
toughness = unit.Toughness,
wounds = unit.Wounds,
attacks = unit.Attacks,
leadership = unit.Leadership,
savingThrow = unit.SaveThrow,
specialRules = unit.SpecialRules,
dedicatedTransport = unit.DedicatedTransport,
options = unit.Options,
armour = unit.Armour,
weapons = unit.Weapons
});
}
编辑:所以看起来你可以new String(unit.Composition.ToCharArray())
在数组内做。我不认为这更具可读性或写起来更快。
properites.AddRange(new string[1]{
new String(unit.Composition.ToCharArray())}