如何将两个对象相加?

时间:2011-09-13 22:45:28

标签: c# types sum operator-keyword

我想做一个pareses文本的应用程序。到目前为止,我有一个名为Result的类,它保存值并键入等式的每个部分。

public enum ResultType
{
    Int32,
    Double,
    Boolean,
    Color,
    DateTime,
    String,
    Undefined,
    Void
}

public class Result
{
    public object Value { get; set; }
    public ResultType Type { get; set; }
}

可能的结果可能是:

 5 : Int32
 true : Boolean 
 DADACC : Color 
 "Hello World!" : String 
 10.0 : Double 
 13/11/1986 : DateTime

现在我要总结/除/ / / ...两个结果,但我真的不想做所有的工作。在C#中,您可以将它们混合在一起并得到答案。

var value = "Hello" + 2.0 + 4 + DateTime.Today; (value = "Hello2413/09/2011 12:00:00 a.m.")

有一种简单的方法可以解决这个问题吗?或者我必须自己弄清楚所有组合?我想的是:

var Operator = "+"; // or "-","*","/","^","%"
var sum = DoTheCSharpOperation(Operator, ResultA.Value, ResultB.Value)
var sumResult = new Result(sum);

1 个答案:

答案 0 :(得分:8)

这听起来像是“动态”关键字的完美应用:

using System;
using System.Diagnostics;

namespace ConsoleApplication33 {
  public static class Program {
    private static void Main() {
      var result1=DoTheCSharpOperation(Operator.Plus, 1.2, 2.4);
      var result2=DoTheCSharpOperation(Operator.Plus, "Hello", 2.4);
      var result3=DoTheCSharpOperation(Operator.Minus, 5, 2); 

      Debug.WriteLine(result1); //a double with value 3.6
      Debug.WriteLine(result2); //a string with value "Hello2.4"
      Debug.WriteLine(result3); //an int with value 3
    }

    public enum Operator {
      Plus,
      Minus
    }

    public static object DoTheCSharpOperation(Operator op, dynamic a, dynamic b) {
      switch(op) {
        case Operator.Plus:
          return a+b;
        case Operator.Minus:
          return a-b;
        default:
          throw new Exception("unknown operator "+op);
      }
    }
  }
}