I want to do an application that pareses text. So far, I have a class called Result, that holds the value and type each part of an equation.
public enum ResultType
{
Int32,
Double,
Boolean,
Color,
DateTime,
String,
Undefined,
Void
}
public class Result
{
public object Value { get; set; }
public ResultType Type { get; set; }
}
Possible Result's could be:
5 : Int32
true : Boolean
DADACC : Color
"Hello World!" : String
10.0 : Double
13/11/1986 : DateTime
Now I want to开发者_开发百科 sum/divide/pow/... two Results but I really don´t want to do all the work. In C#, you can mix them all together and get an answer.
var value = "Hello" + 2.0 + 4 + DateTime.Today; (value = "Hello2413/09/2011 12:00:00 a.m.")
Is there an easy way to handle this? Or do I have to figure out all combos by myself? I´m thinking about something like:
var Operator = "+"; // or "-","*","/","^","%"
var sum = DoTheCSharpOperation(Operator, ResultA.Value, ResultB.Value)
var sumResult = new Result(sum);
This sounds to me like a perfect application for the "dynamic" keyword:
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);
}
}
}
}
精彩评论