如何获得一个类型中定义的运算符.net

如何获得一个类型中定义的运算符.net

问题描述:

我想要获取特定类型的已定义的运算符的列表,以查看可以应用于该类型的操作类型。如何获得一个类型中定义的运算符.net

例如,类型的Guid支持操作==!=

因此,如果用户想要应用< =对于Guid类型,我可以在发生异常之前处理这种情况。

或者如果我有运营商列表,我可以强制用户只使用列表中的操作。

在对象浏览器中看到运算符,因此可能有一种方法可以通过反射访问它们,但我找不到这种方式。

任何帮助将不胜感激。

获取方法与Type.GetMethods,然后用MethodInfo.IsSpecialName发现运营商,转换等。下面是一个例子:

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); 
      } 
     } 
    } 
} 
+0

嗨,感谢您的快速回复! 我认为这适用于大多数类型,但当我尝试Int32时,它返回一个空集。 有什么建议吗? – Cankut 2009-09-11 19:26:55

+2

是的,原始类型的操作符是这样的“有趣”。我怀疑你基本上不得不对它们进行硬编码。不要忘记,基元不包括'decimal','DateTime','TimeSpan或'Guid'。 – 2009-09-11 19:28:59

+0

非常感谢:) – Cankut 2009-09-11 19:30:48

C#4.0具有动态语言运行库的功能,如何使用dynamic型又如何?

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's 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()); 
    } 
} 
}