How do I find the return type of a method with Sys

2019-04-18 00:02发布

how do I find out the return type of a method from the MethodBase? I'm using PostSharp and trying to override the CompileTimeValidate(MethodBase method) method to make sure the attribute is applied to a method with the correct signature.

Thanks,

4条回答
\"骚年 ilove
2楼-- · 2019-04-18 00:47

Try something like this. MethodInfo has the property but MethodBase is used for constructors as well, and they do not have a return type.

MethodBase b = this.GetType().GetMethods().First(); 
if(b is MethodInfo)
    MessageBox.Show((b as MethodInfo).ReturnType.Name);
查看更多
仙女界的扛把子
3楼-- · 2019-04-18 00:57

Try the MethodInfo.ReturnType property.

To get the return type property, first get the Type. From the Type, get the MethodInfo. From the MethodInfo, get the ReturnType.

It seems like you can't do it with MethodBase...

http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.returntype.aspx

查看更多
聊天终结者
4楼-- · 2019-04-18 01:02

MethodBase is used as a base class of MethodInfo which has a property ReturnType.

You could try and cast to an instance of MethodInfo and check that property.

查看更多
女痞
5楼-- · 2019-04-18 01:07

MethodBase itself does not have a return type because in addition to normal methods it also is used to represent methods, such as constructors, which have no return type. Instead you need to see if it's an instance of MethodInfo and check that for the ReturnType property.

CompileTimeValidate(MethodBase method) {
  var normalMethod = method as MethodInfo;
  if( normalMethod != null) {
    ValidateReturnType(normalMethod.ReturnType);
  }
}
查看更多
登录 后发表回答