簡體   English   中英

如何在C#中使用System.Reflection.MethodBase找到方法的返回類型?

[英]How do I find the return type of a method with System.Reflection.MethodBase in C#?

如何從MethodBase中找出方法的返回類型? 我正在使用PostSharp並嘗試覆蓋CompileTimeValidate(MethodBase方法)方法以確保該屬性應用於具有正確簽名的方法。

謝謝,

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);

嘗試MethodInfo.ReturnType屬性。

要獲取返回類型屬性,請首先獲取Type Type中獲取MethodInfo MethodInfo ,獲取ReturnType

看起來你不能用MethodBase來做...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM