How to verify whether a type overloads/supports a certain operator?

后端 未结 3 1347
孤城傲影
孤城傲影 2020-12-10 15:18

How can I check whether a certain type implements a certain operator?

struct CustomOperatorsClass
{
    public int Value { get; private set; }


    public C         


        
相关标签:
3条回答
  • 2020-12-10 16:08

    There is a quick and dirty way to find out, and it works for both built-in and custom types. Its major drawback is that it relies on exceptions in a normal flow, but it gets the job done.

     static bool HasAdd<T>() {
        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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 16:08

    An extension method called HasAdditionOp like this:

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

    Note that IsSpecialName prevents a normal method with the name "op_Addition";

    0 讨论(0)
  • 2020-12-10 16:09

    You should check if class have method with op_Addition name You can find overloaded method names here,
    Hope this helps

    0 讨论(0)
提交回复
热议问题