gpt4 book ai didi

c# - * 运算符和类型转换器

转载 作者:行者123 更新时间:2023-11-30 17:44:39 24 4
gpt4 key购买 nike

我有以下内容。它按预期工作:

using System;
namespace Whatever {
public class DoubleWrapper {
public double Payload { get; set; }
public DoubleWrapper(double payload) {
this.Payload = payload;
}
public static implicit operator DoubleWrapper(double x) {
DoubleWrapper r = new DoubleWrapper(x);
return r;
}
public static implicit operator double(DoubleWrapper wrapper) {
double r = wrapper.Payload;
return r;
}
public DoubleWrapper Times(DoubleWrapper multiplyByMe) {
DoubleWrapper r = this * multiplyByMe; // does compile
return r;
}
}
}

但是,如果我将“double”替换为“Complex”,则会出现编译错误:

using System;
using System.Numerics;
namespace Whatever {
public class ComplexWrapper {
public Complex Payload { get; set; }
public ComplexWrapper(Complex payload) {
this.Payload = payload;
}
public static implicit operator ComplexWrapper(Complex x) {
ComplexWrapper r = new ComplexWrapper(x);
return r;
}
public static implicit operator Complex(ComplexWrapper wrapper) {
Complex r = wrapper.Payload;
return r;
}
public ComplexWrapper Times(ComplexWrapper multiplyByMe) {
ComplexWrapper r = this * multiplyByMe; // ERROR: Operator '*' cannot be applied to operands of type Whatever.ComplexWrapper and Whatever.ComplexWrapper.
return r;
}

解决方法并不难——我可以像这样替换行:

      ComplexWrapper r = this.Payload * multiplyByMe; //WORKS

我确实验证了 * 符号对 double 和 System.Numerics.Complex 都有效。它确实:

namespace SomewhereElse { // different namespace
public static class TestTimes { // builds just fine
public static void Products() {
double x1 = 4;
double x2 = 5;
double product = x1 * x2;
Complex z1 = new Complex(3, 4);
Complex z2 = new Complex(3, -4);
Complex zProduct = z1 * z2;
}
}
}

为什么构建了我的 DoubleWrapper 类,而不是我的 ComplexWrapper?

最佳答案

在您的 block 1 上,类型被隐式转换为 double,因此乘法有效,但在您的 block 2 上没有乘法运算符。

如果您在第 2 类中添加以下代码,错误将消失。

    public static ComplexWrapper operator *(ComplexWrapper a, ComplexWrapper b)
{
var complex = a.Payload * b.Payload;
return complex;
}

编辑:精炼答案/第二种方法

编译器似乎将该类型提升为 ComplexWrapper,这就是产生该错误的原因。

通过简单地将 this 转换为 Complex 错误也会消失:

    public ComplexWrapper Times(ComplexWrapper multiplyByMe)
{
ComplexWrapper r = (Complex)this * multiplyByMe;
// ERROR: Operator '*' cannot be applied to operands of type Whatever.ComplexWrapper and Whatever.ComplexWrapper.
return r;
}

关于c# - * 运算符和类型转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29195088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com