use*_*443 22 c# reflection operator-overloading operators system.reflection
在我的小项目中,我正在使用System.Reflection类来生成可执行代码.我需要调用+自定义类型的运算符.有谁知道如何使用C#反射调用自定义类的自定义运算符?
Moh*_*han 27
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_OnesComplement ? ?
? 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 <type> ? op_Implicit ? Implicit type conversion ?
? explicit operator <type> ? op_Explicit ? Explicit type conversion ?
? operator true ? op_True ? ?
? operator false ? op_False ? ?
???????????????????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
所以要检索struct 的operator+方法DateTime,你需要写:
MethodInfo mi = typeof(DateTime).GetMethod("op_Addition",
BindingFlags.Static | BindingFlags.Public );
Run Code Online (Sandbox Code Playgroud)
typeof(A).GetMethod("op_Addition").Invoke(null, instance1, instance2);
Run Code Online (Sandbox Code Playgroud)