哪里是在op_addition [整型,浮点,双] [英] where is op_addition in [int,float,double]
问题描述
虚拟代码:
public object Addition(object a, object b)
{
var type = a.GetType();
var op = type.GetMethod("op_Addition", BindingFlags.Static | BindingFlags.Public);
return op.Invoke(null, new object[] { a, b });
}
这方法,INT /浮点/双精度抱怨,说找不到这些方法(op_Addition)。
This method complains with int/float/double,that can't find these methods(op_Addition).
因此,如何构建一个通用除了方法?
推荐答案
是的,他们不存在哪像那个成员运营商定制 - 有内置的IL指令而不是
Yes, they're not custom operators which exist as members like that - there are built-in IL instructions instead.
(同样是的几乎的真正的字符串连接,除了那里的C#编译器生成一个呼叫 string.Concat
)
(The same is almost true for string concatenation, except there the C# compiler builds a call to string.Concat
.)
如果您正在使用C#4和.NET 4,最简单的方法是使用动态类型:
If you're using C# 4 and .NET 4, the simplest approach is to use dynamic typing:
public dynamic Addition(dynamic x, dynamic y)
{
return x + y;
}
有关早期版本中,你需要特殊情况某些类型:(
For earlier versions, you'll need to special-case certain types :(
目前还不清楚你的背景是什么,但你会发现马克Gravell的的文章通用的运营商有趣。
It's not clear what your context is, but you may find Marc Gravell's article on generic operators interesting.
这篇关于哪里是在op_addition [整型,浮点,双]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!