其他分享
首页 > 其他分享> > 可以获取“运算符”结果的参考吗?

可以获取“运算符”结果的参考吗?

作者:互联网

是否可以某种方式获取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和一个赋值.您可以更改左侧作为运算符的一部分-但这很邪恶. Add方法似乎是最干净的设计恕我直言.

标签:operator-overloading,operator-keyword,c
来源: https://codeday.me/bug/20191029/1956842.html