当我不知道它们在.NET中的类型时,如何将两个数字加在一起?例如,您将如何实现以下功能?
public object AddTwoNumbers(object left, object right)
{
/* What goes here? */
}
Run Code Online (Sandbox Code Playgroud)
假设'left'和'right'参数是(盒装)值类型,例如Int32,double,Decimal等.你不知道具体的类型,你只知道它是数字,并且添加对它有意义.
谢谢!
Jon*_*eet 14
在.NET 3.5及更早版本中,最简单的方法可能是测试每种类型 - 或者更确切地说,每种类型的组合 - 您可以处理,适当地转换并执行相关操作.您可以尝试使用反射来获取适当的运算符,但这可能会有一些奇怪的极端情况.
在.NET 4.0和C#4中,这很容易:
public object AddTwoNumbers(object left, object right)
{
dynamic x = left;
dynamic y = right;
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
如果你愿意接受left并且right必须是同一类型的限制,那也不是太糟糕:
using System;
using System.Collections.Generic;
public class Test
{
static Dictionary<Type, Func<object, object, object>> Adders =
new Dictionary<Type, Func<object, object, object>>
{
{ typeof(int), (x, y) => (int) x + (int) y },
{ typeof(double), (x, y) => (double) x + (double) y },
{ typeof(decimal), (x, y) => (decimal) x + (decimal) y },
{ typeof(long), (x, y) => (long) x + (long) y },
// etc
};
static object Add(object left, object right)
{
if (left.GetType() != right.GetType())
{
throw new ArgumentException("Types must be the same");
}
Func<object, object, object> adder;
if (!Adders.TryGetValue(left.GetType(), out adder))
{
throw new ArgumentException
("I don't have an adder for that type");
}
return adder(left, right);
}
static void Main()
{
Console.WriteLine(Add(3, 4));
Console.WriteLine(Add(3.5m, 4.2m));
Console.WriteLine(Add(3.5, 4.8));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
283 次 |
| 最近记录: |