的BindingFlags为Type.GetMethods不包括物业accesors [英] BindingFlags for Type.GetMethods excluding property accesors

查看:107
本文介绍了的BindingFlags为Type.GetMethods不包括物业accesors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经得到了下面的程序:

Suppose I've got the following program:

namespace ReflectionTest
{
    public class Example
    {
        private string field;

        public void MethodOne() { }

        public void MethodTwo() { }

        public string Property
        {
            get { return field; }
            set { this.field = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            iterate(typeof(Example));

            Console.ReadLine();
        }

        public static void iterate(Type type)
        {
            MethodInfo[] methods = type.GetMethods(
                BindingFlags.DeclaredOnly |
                BindingFlags.Instance |
                BindingFlags.Public);

            foreach (MethodInfo mi in methods)
            {
                Console.WriteLine(mi.Name);
            }
        }
    }
}

当我运行程序我得到以下输出:

When I run the program I'm getting the following output:

MethodOne
MethodTwo
get_Property
set_Property

我想跳过财产accesor方法。我试着用不同的<一个href="http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx"><$c$c>BindingFlags,例如,〜BindingFlags.SetProperty ,但没有运气。目前唯一的办法我发现跳过这些方法被重写迭代函数:

I want to skip the property accesor methods. I've tried with different BindingFlags, for instance, ~BindingFlags.SetProperty, but with no luck. At the moment the only way I've found to skip those methods is rewriting the iterate function to:

public static void iterate(Type type)
{
    MethodInfo[] methods = type.GetMethods(
        BindingFlags.DeclaredOnly |
        BindingFlags.Instance |
        BindingFlags.Public);

    foreach (MethodInfo mi in methods)
    {
        if (mi.IsSpecialName) continue;
        Console.WriteLine(mi.Name);
    }
}

你知道的BindingFlags 我应该用什么呢?

非常感谢你。

嗯,我应该解释说,该项目实际上是建筑自动单元测试模板,这样我就可以跳过所有的特殊方法。感谢您对IsSpecialName附加信息:)

Well, I should have explained that the project is actually for building automatically templates for unit testing, so I can skip all the special methods. Thanks for the additional information on IsSpecialName :)

LINQ?真?哇。无论如何,这个项目是.NET 2.0,以便LINQ是(可惜)不是一个选项。

LINQ? Really? Wow. Anyway, this project is .NET 2.0 so LINQ is (sadly) not an option.

推荐答案

从我的头顶:

mi.IsSpecialName &&( mi.Name.StartsWith("set_") || mi.Name.StartsWith("get_"))

应该得到你全部搞定。 SpecialName超过属性访问器(事件添加/删除方法在这里算好),这就是为什么你必须检查的名称为好。

should get you all set. SpecialName is more than property accessors (event add/remove methods count here as well), that's why you have to check the names as well.

您可以使用LINQ为以及:)

You can use LINQ for that as well :)

这篇关于的BindingFlags为Type.GetMethods不包括物业accesors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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