c# - 如何求和两个对象?

标签 c# types sum operator-keyword

我想做一个解析文本的应用程序。到目前为止,我有一个名为 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

现在我想求和/除/pow/...两个结果,但我真的不想做所有的工作。在 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);

最佳答案

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

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

关于c# - 如何求和两个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7409457/

相关文章:

javascript - 使用 Numbers.js 对值求和

c# - 如何防止 Selenium C# 中 PageFactory 中的 StaleElementReferenceException?

c# - 使用 `async` lambda 和 `Task.Run()` 是多余的吗?

c++ - 为什么 INT_MIN 的绝对值与 INT MAX 不同?

linux - 可变长度表的 Bash 列总和

Python sum() 在导入 numpy 后有不同的结果

c# - 添加访问列表

c# - 如何实现一个已经有其他接口(interface)的接口(interface)?

c# 使用 lambda 检查对象是否属于某种动态类型(通过参数传递)

types - 前导单引号是什么意思?