我试图获取一个类型的所有方法的列表。 Type 提供了 GetMethods 方法来执行此操作。但不幸的是,它似乎没有正确实现。只要反射类型上没有没有重写的通用方法,它就可以正常工作。在这种特殊情况下,会抛出 MethodAccessException。
有人有解决此 WP7 错误的方法吗?如果返回除通用方法之外的所有方法,我很好。
这是一个将抛出异常的类的示例。注意:none 泛型返回值是为了证明返回值不涉及问题。此外,可以将基方法更改为抽象方法,问题仍然存在。
public abstract class BaseClassWithGenericMethod
{
public virtual System.Collections.IList CreateList<T>()
{
return new List<T>();
}
}
public class DerivedClassWithGenericMethod
: BaseClassWithGenericMethod
{
public override System.Collections.IList CreateList<T>()
{
return new List<T>();
}
}
最佳答案
我会全部获取它们(注意 GetMethods
中的 BindingFlags.DeclaredOnly
),然后过滤掉那些通用方法(MethodInfo.IsGenericMethod
).
对不起 VB,我知道现在全世界都想要 C#,但是...
Public Function GetListOfMethods() As List(Of MethodInfo)
Dim d As New DerivedClassWithGenericMethod
Dim myArrayMethodInfo() As Reflection.MethodInfo
myArrayMethodInfo = d.GetType.GetMethods(BindingFlags.Instance _
Or BindingFlags.Public _
Or BindingFlags.DeclaredOnly)
Dim myArrayMethodInfoList As New List(Of MethodInfo)
For Each m As MethodInfo In myArrayMethodInfo
If Not m.IsGenericMethod Then
myArrayMethodInfoList.Add(m)
End If
Next
Return myArrayMethodInfoList
End Function
我刚刚使用您的示例类在 WP7 上进行了测试,它运行良好。
关于c# - WP7 : Type. GetMethods 抛出 MethodAccessException。这个错误有解决方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5639376/