Csharp/C#教程:如何使用Reflection调用自定义运算符分享


如何使用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

喜欢

上述就是C#学习教程:如何使用Reflection调用自定义运算符分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1255881.html

(0)
上一篇 2022年11月16日
下一篇 2022年11月16日

精彩推荐