如何validation类型是否重载/支持某个运算符?

如何检查某种类型是否实现某个运算符?

struct CustomOperatorsClass { public int Value { get; private set; } public CustomOperatorsClass( int value ) : this() { Value = value; } static public CustomOperatorsClass operator +( CustomOperatorsClass a, CustomOperatorsClass b ) { return new CustomOperatorsClass( a.Value + b.Value ); } } 

以下两次检查应该返回true

 typeof( CustomOperatorsClass ).HasOperator( Operator.Addition ) typeof( int ).HasOperator( Operator.Addition ) 

有一种快速而肮脏的方法可以找到它,它适用于内置和自定义类型。 它的主要缺点是它依赖于正常流程中的exception,但它完成了工作。

  static bool HasAdd() { var c = Expression.Constant(default(T), typeof(T)); try { Expression.Add(c, c); // Throws an exception if + is not defined return true; } catch { return false; } } 

您应该检查类是否具有op_Addition名称的方法您可以在此处找到重载的方法名称,
希望这可以帮助

一个名为HasAdditionOp的扩展方法,如下所示:

 pubilc static bool HasAdditionOp(this Type t) { var op_add = t.GetMethod("op_Addition"); return op_add != null && op_add.IsSpecialName; } 

请注意, IsSpecialName阻止名为“op_Addition”的普通方法;