Is there a better way to express this #6446
-
public struct Fight
{
public float hp;
public float maxHp;
public float atk;
public float def;
public float shield;
public int level;
public float gold;
public float exp;
public static Fight operator +(Fight a, Fight b) => new Fight()
{
hp = a.hp + b.hp,
maxHp = a.maxHp + b.maxHp,
atk = a.atk + b.atk,
def = a.def + b.def,
shield = a.shield + b.shield,
level = a.level + b.level,
gold = a.gold + b.gold,
exp = a.exp + b.exp,
};
public static Fight operator -(Fight a, Fight b) => new Fight()
{
hp = a.hp - b.hp,
maxHp = a.maxHp - b.maxHp,
atk = a.atk - b.atk,
def = a.def - b.def,
shield = a.shield - b.shield,
level = a.level - b.level,
gold = a.gold - b.gold,
exp = a.exp - b.exp,
};
} It's too dangerous to hand write such code. One way I'm currently learning is to do these things by reflection. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Is there a language question here? Writing code like that isn't unique to C# or these use cases, you do need to be careful. You mitigate the danger through many means, such as just having good unit tests. You could also use analyzers to detect when you've missed a field, or source generators to emit the operators for you. You could also use reflection and expression trees combined into a delegate, which would give you a performance hit up front but wouldn't be appreciably slower from that point on. |
Beta Was this translation helpful? Give feedback.
-
At 1st glance, it is questionable to:
|
Beta Was this translation helpful? Give feedback.
-
If such pattern is common in your project, it's gonna worth to write a custom source generator. |
Beta Was this translation helpful? Give feedback.
Is there a language question here? Writing code like that isn't unique to C# or these use cases, you do need to be careful. You mitigate the danger through many means, such as just having good unit tests. You could also use analyzers to detect when you've missed a field, or source generators to emit the operators for you. You could also use reflection and expression trees combined into a delegate, which would give you a performance hit up front but wouldn't be appreciably slower from that point on.