如何使用Reflection调用自定义运算符

在我的小项目中,我使用System.Reflection类来生成可执行代码。 我需要调用自定义类型的+运算符。 有谁知道如何使用C#reflection调用自定义类的自定义运算符?

C#编译器将重载的运算符转换为名为op_XXXX函数,其中XXXX是操作。 例如, operator +编译为op_Addition

以下是可重载运算符及其各自方法名称的完整列表:

 ┌──────────────────────────┬───────────────────────┬──────────────────────────┐ │ Operator │ Method Name │ Description │ ├──────────────────────────┼───────────────────────┼──────────────────────────┤ │ operator + │ op_UnaryPlus │ Unary │ │ operator - │ op_UnaryNegation │ Unary │ │ operator ++ │ op_Increment │ │ │ operator -- │ op_Decrement │ │ │ operator ! │ op_LogicalNot │ │ │ operator + │ op_Addition │ │ │ operator - │ op_Subtraction │ │ │ operator * │ op_Multiply │ │ │ operator / │ op_Division │ │ │ operator & │ op_BitwiseAnd │ │ │ operator | │ op_BitwiseOr │ │ │ operator ^ │ op_ExclusiveOr │ │ │ operator == │ op_Equality │ │ │ operator != │ op_Inequality │ │ │ operator < │ op_LessThan │ │ │ operator > │ op_GreaterThan │ │ │ operator <= │ op_LessThanOrEqual │ │ │ operator >= │ op_GreaterThanOrEqual │ │ │ operator << │ op_LeftShift │ │ │ operator >> │ op_RightShift │ │ │ operator % │ op_Modulus │ │ │ implicit operator  │ op_Implicit │ Implicit type conversion │ │ explicit operator  │ op_Explicit │ Explicit type conversion │ │ operator true │ op_True │ │ │ operator false │ op_False │ │ └──────────────────────────┴───────────────────────┴──────────────────────────┘ 

因此,要检索DateTime结构的operator+方法,您需要编写:

 MethodInfo mi = typeof(DateTime).GetMethod("op_Addition", BindingFlags.Static | BindingFlags.Public ); 
 typeof(A).GetMethod("op_Addition").Invoke(null, instance1, instance2); 

考虑将您的自定义运算符作为Class property 。 然后通过reflection访问property及其value

喜欢

 PropertyInfo pinfo = obj.GetType().GetProperty("CustomOperator", BindingFlags.Public | BindingFlags.Instance); string customOperator = pinfo.GetValue(obj,null) as string;