为什么我可以';t使用“+";with type object或者什么类型的运算符可以与object一起使
本文关键字:object 类型 什么 运算符 一起 或者 type 我可以 使用 with quot | 更新日期: 2023-09-27 18:20:31
什么类型的运算符可用于对象类?
public static void testing()
{
object test = 10;
object x = "a";
object result = test + x;//compiler error
}
为什么我不能将+
与对象类型一起使用?
默认情况下,并非每个对象都支持+
、-
或其他运算符。想象一下以下类别:
public class Weight
{
public int Value {get;set;}
}
以及以下实例(例如计算组合权重):
var w1 = new Weight { Value = 1 };
var w2 = new Weight { Value = 2 };
执行以下操作将导致编译器错误:
var result = w1 + w2;
错误看起来像:
运算符"+"不能应用于类型为"Weight"answers"Weight""的操作数
您必须将+
运算符重载为:
public class Weight
{
public int Value {get;set;}
public static Weight operator +(Weight w1, Weight w2)
{
return new Weight { Value = w1.Value + w2.Value };
}
}
现在你可以做:
var result = w1 + w2;
Console.WriteLine(result.Value); //Writes: 3
-
操作员也是如此:
public static Weight operator -(Weight w1, Weight w2)
{
return new Weight { Value = w1.Value - w2.Value };
}
进一步阅读:
- C#运算符
- 可重载运算符