How to get specific operators for type in .net

I am trying to get a list of specific operators for a particular type to see what operations can be applied to this type.

For example, the Guid type supports operations == and ! = .

So, if the user wants to apply the <= operation for the Guid type, I can handle this situation before an exception occurs.

Or, if I had a list of operators, I can force the user to use only the operations in the list.

The operators are visible in the object browser, so there may be a way to access them through reflection, but I could not find this.

Any help would be appreciated.

+6
operators reflection c #
source share
2 answers

Get methods using Type.GetMethods , then use MethodInfo.IsSpecialName to find operators, conversions, etc. Here is an example:

 using System; using System.Reflection; public class Foo { public static Foo operator +(Foo x, Foo y) { return new Foo(); } public static implicit operator string(Foo x) { return ""; } } public class Example { public static void Main() { foreach (MethodInfo method in typeof(Foo).GetMethods()) { if (method.IsSpecialName) { Console.WriteLine(method.Name); } } } } 
+10
source share

C # 4.0 has a dynamic language execution feature, so what about using a dynamic type?

 using Microsoft.CSharp.RuntimeBinder; namespace ListOperatorsTest { class Program { public static void ListOperators(object inst) { dynamic d = inst; try { var eq = d == d; // Yes, IntelliSense gives a warning here. // Despite this code looks weird, it will do // what it supposed to do :-) Console.WriteLine("Type {0} supports ==", inst.GetType().Name); } catch (RuntimeBinderException) { } try { var eq = d <= d; Console.WriteLine("Type {0} supports <=", inst.GetType().Name); } catch (RuntimeBinderException) { } try { var eq = d < d; Console.WriteLine("Type {0} supports <", inst.GetType().Name); } catch (RuntimeBinderException) { } try { var add = d + d; Console.WriteLine("Type {0} supports +", inst.GetType().Name); } catch (RuntimeBinderException) { } try { var sub = d - d; Console.WriteLine("Type {0} supports -", inst.GetType().Name); } catch (RuntimeBinderException) { } try { var mul = d * d; Console.WriteLine("Type {0} supports *", inst.GetType().Name); } catch (RuntimeBinderException) { } try { try { var div = d / d; } catch (DivideByZeroException) { } Console.WriteLine("Type {0} supports /", inst.GetType().Name); } catch (RuntimeBinderException) { } } private struct DummyStruct { } static void Main(string[] args) { ListOperators(0); ListOperators(0.0); DummyStruct ds; ListOperators(ds); ListOperators(new Guid()); } } } 
+4
source share

All Articles