gpt4 book ai didi

c# - 无法为对象类重载运算符 '+'

转载 作者:行者123 更新时间:2023-11-30 18:53:00 25 4
gpt4 key购买 nike

我在 c# 中有两个或多个 object 类的变量,它们具有整数值。我想重载“+”运算符,这样我就不必在想要添加或减去它们时转换这些变量。下面是我的代码:

public static object operator +( object obj1, object obj2)
{
object o = Convert.toint32(obj1) + Convert.toint32(obj2);
return o;
}

不,问题是我收到一条错误消息,提示 “二元运算符的一个参数必须是包含类型”

为什么会这样?任何帮助表示赞赏!

最佳答案

编译器错误告诉您确切出了什么问题 - 如果您要创建自定义二元运算符,至少有一个参数类型(对于操作数)必须与您在其中声明运算符的类型(或它的可为空的版本,对于值类型)。

这是 C# 4 specification 的第 10.10.2 节中规定的:

The following rules apply to binary operator declarations, where T denotes the instance type of the class or struct that contains the operator declaration:

  • A binary non-shift operator must take two parameters, at least one of which must have type T or T?, and can return any type.
  • A binary << or >> operator must take two parameters, the first of which must have type T or T? and the second of which must have type int or int?, and can return any type.

我个人会尽量避免使用 object 类型的变量如果你知道它们实际上是 int值。为什么没有 int变量代替?

如果您使用的是 C# 4,另一种选择是将它们设为 dynamic变量,运算符重载将在执行时而不是编译时应用。

关于c# - 无法为对象类重载运算符 '+',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6437339/

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