在我的小项目中,我使用System.Reflection类来生成可执行代码。我需要调用自定义类型的+运算符。有谁知道如何使用C#反射调用自定义类的自定义运算符?
发布于 2012-06-20 13:43:14
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 │ │
└──────────────────────────┴───────────────────────┴──────────────────────────┘因此,要检索DateTime结构的operator+方法,您需要编写:
MethodInfo mi = typeof(DateTime).GetMethod("op_Addition",
BindingFlags.Static | BindingFlags.Public );发布于 2012-06-20 13:38:00
typeof(A).GetMethod("op_Addition").Invoke(null, instance1, instance2);发布于 2012-06-20 13:32:50
考虑让您的自定义操作员作为您的Class的property。然后通过reflection访问property及其value。
喜欢
PropertyInfo pinfo = obj.GetType().GetProperty("CustomOperator", BindingFlags.Public | BindingFlags.Instance);
string customOperator = pinfo.GetValue(obj,null) as string;https://stackoverflow.com/questions/11113259
复制相似问题