【发布时间】:2012-06-22 05:13:49
【问题描述】:
在我的小项目中,我使用System.Reflection 类来生成可执行代码。我需要调用自定义类型的+ 运算符。有人知道如何使用 C# 反射调用自定义类的自定义运算符吗?
【问题讨论】:
标签: c# reflection operator-overloading operators system.reflection
在我的小项目中,我使用System.Reflection 类来生成可执行代码。我需要调用自定义类型的+ 运算符。有人知道如何使用 C# 反射调用自定义类的自定义运算符吗?
【问题讨论】:
标签: c# reflection operator-overloading operators system.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_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 );
【讨论】:
op_Addition 方法怎么办?
op_Explicit 和op_Implicit(我认为这些名称是不言自明的)。请记住,虽然可以定义多个转换运算符,但需要通过指定参数类型或返回类型(相对于转换的“方向”)来缩小搜索范围。
~了吗?
typeof(A).GetMethod("op_Addition").Invoke(null, instance1, instance2);
【讨论】:
type.GetMethod("op_Subtraction").Invoke(null, new object[] { instance1, instance2 });
考虑将您的自定义运算符设为property 或Class。然后通过reflection 访问property 及其value。
喜欢
PropertyInfo pinfo = obj.GetType().GetProperty("CustomOperator", BindingFlags.Public | BindingFlags.Instance);
string customOperator = pinfo.GetValue(obj,null) as string;
【讨论】: