为什么我不能对类型对象使用“+”或者什么类型的运算符可以与对象一起使用

时间:2014-09-02 10:56:22

标签: c#

哪些类型的运算符可用于对象类?

public static void testing()
{
    object test = 10;
    object x = "a";
    object result = test + x;//compiler error
}

为什么我不能将+用于对象类型?

1 个答案:

答案 0 :(得分:6)

默认情况下,并非每个对象都支持+-等运算符或其他运算符。想象一下下课:

public class Weight
{
    public int Value {get;set;}
}

以下实例(例如计算合并重量):

var w1 = new Weight { Value = 1 };
var w2 = new Weight { Value = 2 };

执行以下操作将导致编译器错误:

var result = w1 + w2;

错误如下:

  

运营商' +'不能应用于类型'重量'的操作数。和'重量'

您必须将+运算符重载到此:

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 };
}

进一步阅读: