c# - 可以得到 "operator"结果的引用吗?

标签 c# operator-overloading operator-keyword

是否有可能在 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/

相关文章:

c++ - 可变参数模板运算符<<

php 对象运算符 -> 没有实例?

c# - 为什么平方根运算这么慢?

c# - 使用 WebClient 将数据发布到 SSRS 报告服务器

c++ - 为什么此类中的复制构造函数、operator= 和引用存在编译问题

c# - 如何使 EF 通过 GroupJoin 急切加载集合导航属性?

c++ - 订单 : An Analysis on Point Sorting

c++ - 流运算符重载问题

c# - 托管网络应用程序

c# - 适用于 Windows Phone 8.1 Silverlight 的数据库