相关疑难解决方法(0)

是否可以在c#中创建一个新的运算符?

我知道你可以超载现有的运营商.我想知道是否可以创建一个新的运算符.这是我的情景.

我要这个:

var x = (y < z) ? y : z;
Run Code Online (Sandbox Code Playgroud)

相当于:

var x = y <? z;
Run Code Online (Sandbox Code Playgroud)

换句话说,我想创建自己的<?运算符.

.net c# operators

59
推荐指数
6
解决办法
2万
查看次数

Scala:方法\运算符重载

以下示例来自"Programming in Scala"一书.给定一个类'Rational'和以下方法定义:

def add(that: Rational): Rational =
    new Rational(
        this.numer * that.denom + that.numer * this.denom,
        this.denom * that.denom
    )
Run Code Online (Sandbox Code Playgroud)

我可以使用带有Int参数的便捷版本成功地重载add方法,并使用上面的定义:

def add(that: Int): Rational =
    add(new Rational(that, 1))
Run Code Online (Sandbox Code Playgroud)

到目前为止没问题.

现在,如果我将方法名称更改为运算符样式名称:

def +(that: Rational): Rational =
    new Rational(
        this.numer * that.denom + that.numer * this.denom,
        this.denom * that.denom
    )
Run Code Online (Sandbox Code Playgroud)

像这样过载:

def +(that: Int): Rational =
    +(new Rational(that, 1))
Run Code Online (Sandbox Code Playgroud)

我得到以下编译错误:

(fragment of Rational.scala):19: error: value unary_+ is not a member of this.Rational
+(new Rational(that, 1))
 ^
Run Code Online (Sandbox Code Playgroud)

为什么编译器要查找该+ …

scala

34
推荐指数
2
解决办法
3万
查看次数

标签 统计

.net ×1

c# ×1

operators ×1

scala ×1