如何在.net中为类型获取定义的运算符 [英] How to get defined operators for a type in .net

查看:69
本文介绍了如何在.net中为类型获取定义的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取特定类型的已定义运算符列表,以查看可以对该类型应用哪种类型的操作.

I'm trying to get the list of defined operators for a specific type in order to see what kind of operations can be applied to that type.

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

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

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

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

或者,如果我可以有运算符列表,则可以强制用户仅使用列表中的运算符.

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

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

The operators are seen in the object browser so there may be a way to access them via reflection but I couldn't find that way.

任何帮助将不胜感激.

推荐答案

使用Type.GetMethods获取方法,然后使用MethodInfo.IsSpecialName查找运算符,转换等.这是一个示例:

Get the methods with Type.GetMethods, then use MethodInfo.IsSpecialName to discover operators, conversions etc. Here's 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);
            }
        }
    }
}

这篇关于如何在.net中为类型获取定义的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆