Is it possible to call value type operators via reflection?

前端 未结 5 1416
别跟我提以往
别跟我提以往 2020-12-09 04:54

As C# operators e.g. +, +=, == are overridable. It lets me think they are sort of methods, thus wonder if there is a way to call them using reflection, on Int32 for instance

5条回答
  •  猫巷女王i
    2020-12-09 05:38

    What exactly is it you want to do? Dealing with the various meanings of operators (primitive (mapped to specific IL instructions), custom (mapped to static methods), and lifted (provided as a pattern by the compiler)) makes this painful. If you just want to use the operators, then it is possible to write code that provides operator support via generics. I have some code for this that is freely available in MiscUtil (description and examples).


    As an untyped example (an note that this isn't hugely efficient, but works):

    object x = 123, y = 345; // now forget that we know that these are ints...
    object result = Expression.Lambda>(
        Expression.Convert(Expression.Add(
            Expression.Constant(x), Expression.Constant(y)),
        typeof(object))).Compile()();
    

提交回复
热议问题