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

后端 未结 3 1368
孤城傲影
孤城傲影 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() {
        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;
        }
    }
    

提交回复
热议问题