在我的小项目中,我正在使用 System.Reflection
类来生成可执行代码。我需要调用自定义类型的 +
运算符。有人知道如何使用 C# 反射调用自定义类的自定义运算符吗?
在我的小项目中,我正在使用 System.Reflection
类来生成可执行代码。我需要调用自定义类型的 +
运算符。有人知道如何使用 C# 反射调用自定义类的自定义运算符吗?
C#编译器将重载的运算符转换为函数,函数名称为op_XXXX
,其中XXXX
表示运算操作。例如,operator +
编译为op_Addition
。
以下是可重载运算符及其相应方法名称的完整列表:
┌──────────────────────────┬───────────────────────┬──────────────────────────┐
│ Operator │ Method Name │ Description │
├──────────────────────────┼───────────────────────┼──────────────────────────┤
│ operator + │ op_UnaryPlus │ Unary │
│ operator - │ op_UnaryNegation │ Unary │
│ operator ++ │ op_Increment │ Unary │
│ operator -- │ op_Decrement │ Unary │
│ operator ! │ op_LogicalNot │ Unary │
│ operator + │ op_Addition │ │
│ operator - │ op_Subtraction │ │
│ operator * │ op_Multiply │ │
│ operator / │ op_Division │ │
│ operator & │ op_BitwiseAnd │ │
│ operator | │ op_BitwiseOr │ │
│ operator ^ │ op_ExclusiveOr │ │
│ operator ~ │ op_OnesComplement │ Unary │
│ 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 );
typeof(A).GetMethod("op_Addition").Invoke(null, instance1, instance2);
type.GetMethod("op_Subtraction").Invoke(null, new object[] { instance1, instance2 });
- Joseph MerdrignacPropertyInfo pinfo = obj.GetType().GetProperty("CustomOperator", BindingFlags.Public | BindingFlags.Instance);
string customOperator = pinfo.GetValue(obj,null) as string;
op_Addition
方法会怎么样? - Şafak Gürop_Explicit
和op_Implicit
(我认为这些名称很容易理解)。但请记住,可以定义多个类型转换运算符,因此需要通过指定参数类型或返回类型(关于转换的“方向”)来缩小搜索范围。 - Grx70~
吗? - Denis535