Type.GetMethods的BindingFlags(不包括属性访问器) [英] BindingFlags for Type.GetMethods excluding property accessors
问题描述
假设我有以下程序:
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方法.我尝试使用其他 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
吗?
Do you know what BindingFlags
should I use?
嗯,我应该已经解释说,该项目实际上是用于自动构建用于单元测试的模板,因此我可以跳过所有特殊方法.感谢您提供有关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 :)
这篇关于Type.GetMethods的BindingFlags(不包括属性访问器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!