0

当我调用 时inter.GetMethods(),它给了我一个方法列表,包括所有的 get 和 set 语句。如何检查每个项目(在 a 中foreach)是否是 get 或 set 语句。

foreach (MethodInfo meth in inter.GetMethods()) Console.WriteLine(meth.Name);
4

1 回答 1

2

Not exactly the most elegant, but it works:

List<MethodInfo> propertyGetterSetters = new List<MethodInfo>();
foreach(PropertyInfo prop in typeof(MyType).GetProperties())
{
    var getter = prop.GetGetMethod();
    var setter = prop.GetSetMethod();

    if (getter != null)
        propertyGetterSetters.Add(getter);

    if (setter != null)
        propertyGetterSetters.Add(setter);
}


List<MethodInfo> nonPropertyMethods = typeof(MyType).GetMethods().Except(propertyGetterSetters).ToList();

You could also use MethodInfo.IsSpecialName, but that can also pick up on other special cases other than just properties, but if you have a simple class that you can test and see that it works, you can use it instead. I wouldn't recommend it; I'd rather just use a utility method like I have above:

var nonPropertyMethods = typeof(MyType).GetMethods().Where(m => !m.IsSpecialName);

于 2012-11-16T02:29:30.223 回答