是否有可能在 C# 中获取重载运算符结果的引用,这样您就不必使用“new”关键字来创建临时结果(之后返回)?
这是我遇到的一个问题示例:
public class Stats {
public float someField;
public float someOtherField;
public static Stats operator +(Stats a, Stats b) {
Stats c = new Stats(); // I don't want a new one, can I access operators result directly?
c.someField = a.someField + b.someField;
c.someOtherField = a.someOtherField + b.someOtherField;
return c;
}
/*
// This is what I want to achieve, but it would be cooler if static and with the "+"
public Add(SomeType a) {
someField += a.someField;
someOtherField += a.someOtherField
}
*/
}
public class StatObserver {
public Stats statsToObserve;
public Output() {
print(statsToObserve.someField);
}
}
public class Class {
public Stats firstStats = new Stats();
firstStats.someField = 1.5f;
public StatObserver showStats = new StatObserver();
showStats.statsToObserve = firstStats;
public Stats nextStats = new Stats();
nextStats.someField = 3.4f;
// now the tricky part
firstStats += nextStats; // C# handles the += itself correctly
showStats.Output(); // prints "1.5"
// you have to update the observer to get the new value
// it's kind of stupid, because you have to treat firstStats like a value type buts its not
showStats.statsToObserve = firstStats;
showStats.Output(); // prints "4.9"
}
最佳答案
您不能直接重载 +=
运算符 - 它被编译为添加和赋值。您可以将左侧作为 +
运算符的一部分进行变异 - 但那将是邪恶的。 Add
方法似乎是最干净的设计恕我直言。
关于c# - 可以得到 "operator"结果的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538231/