是否有办法使用反射来添加每个变量?例如,手工操作的方法是:
public class PlayerStats {
public float Health;
public float HealthRegen;
public float Mana;
public float ManaRegen;
public float Stamina;
public float StaminaRegen;
public float Armor;
public float AttackDamage;
public float AttackDamageCritical;
public float AttaackSpeed;
public float AttackRange;
public float MovementSpeed;
public static PlayerStats operator +(PlayerStats ps1, PlayerStats ps2){
PlayerStats returnPlayerStats = new PlayerStats();
returnPlayerStats.Health = ps1.Health + ps2.Health;
returnPlayerStats.HealthRegen = ps1.HealthRegen + ps2.HealthRegen;
returnPlayerStats.Mana = ps1.Mana + ps2.Mana;
returnPlayerStats.ManaRegen = ps1.ManaRegen + ps2.ManaRegen;
returnPlayerStats.Stamina = ps1.Stamina + ps2.Stamina;
returnPlayerStats.StaminaRegen = ps1.StaminaRegen + ps2.StaminaRegen;
returnPlayerStats.Armor = ps1.Armor + ps2.Armor;
returnPlayerStats.AttackDamage = ps1.AttackDamage + ps2.AttackDamage;
returnPlayerStats.AttackDamageCritical = ps1.AttackDamageCritical + ps2.AttackDamageCritical;
returnPlayerStats.AttaackSpeed = ps1.AttaackSpeed + ps2.AttaackSpeed;
returnPlayerStats.Health = ps1.AttackRange + ps2.AttackRange;
returnPlayerStats.Health = ps1.MovementSpeed + ps2.MovementSpeed;
return returnPlayerStats;
}
}
所以我在想我可以通过使用反射来自动化这个吗?比如:
foreach(var field in typeof(PlayerStats).getFields()){
field.setValue((object)((int)field.getValue(ps1) + (int)field.getValue(ps2)))
}
首先,你最好让它保持原样,因为反射比正常访问要慢得多,并且在操作符中包含它是一个坏主意,因为它们可能被用于循环等,但如果你想达到类似的效果,请执行以下操作:
使用Dictionary查看您的字段都是浮点数,然后您可以添加一个方法到
private Dictionary<string,float> fields = new Dictionary<string,float>()
public PlayerStats()
{
fields.Add("Health", value);
// other fields here
}
public void SetField(string name, float value)
{
if(!fields.ContainsKey(name))
throw new InvalidOperationException("Field doesnt exists");
fields[name] = value;
}
你的类可以有一个默认的字段集,你可以添加到。
+操作符方法将遍历字典中的键,并对两个对象的值求和。
public static PlayerStats operator +(PlayerStats ps1, PlayerStats ps2){
var playerstats = new PlayerStats();
foreach(var key in fields.keys)
{
playerstats[key] = ps1[key] + ps2[key];
}
return playerstats;
}
可以添加强类型访问器作为属性
public float Health
{
get { return fields["Health"]; }
set { field["Health"] = value; }
}