如何从MethodBase中找出方法的返回类型?我正在使用PostSharp,并尝试覆盖CompileTimeValidate(MethodBase method)方法,以确保该属性应用于具有正确签名的方法。
谢谢。
如何从MethodBase中找出方法的返回类型?我正在使用PostSharp,并尝试覆盖CompileTimeValidate(MethodBase method)方法,以确保该属性应用于具有正确签名的方法。
谢谢。
MethodBase
本身没有返回类型,因为除了普通方法外,它还用于表示没有返回类型的方法,例如构造函数。 因此,您需要查看其是否是MethodInfo
的实例,并检查其中的ReturnType
属性。
CompileTimeValidate(MethodBase method) {
var normalMethod = method as MethodInfo;
if( normalMethod != null) {
ValidateReturnType(normalMethod.ReturnType);
}
}
MethodBase被用作MethodInfo的基类,后者拥有一个ReturnType属性。
您可以尝试将其转换为MethodInfo实例,并检查该属性。
MethodInfo
具有该属性,但是对于构造函数使用的是 MethodBase
,它们没有返回类型。MethodBase b = this.GetType().GetMethods().First();
if(b is MethodInfo)
MessageBox.Show((b as MethodInfo).ReturnType.Name);
b
是否为 MethodInfo
,那么直接强制转换 (MethodInfo)b
稍微优于 b as MethodInfo
。 - Adam Robinsonas
。在这种情况下,由于if内部不接受null,请改用(MethodInfo)b
。更好的方法是通过使用as
而不是is
并测试是否为null来避免两次转换的成本。 - BevanMethodInfo.ReturnType
属性。Type
。从 Type
获取 MethodInfo
。从 MethodInfo
获取 ReturnType
。http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.returntype.aspx