2009-11-30 55 views
40

使用反射来获得一个MethodInfo,我想测试返回的类型是否是typeof System.Void。如何测试MethodInfo.ReturnType是否为System.Void的类型?

测试如果System.Int32工作正常

myMethodInfo.ReturnType == typeof(System.Int32) 

myMethodInfo.ReturnType == typeof(System.Void) 

不编译?目前我正在测试名称的字符串表示是否为“System.Void”,这看起来非常错误。

+1

你得到了什么错误构建代码时? – 2009-11-30 14:53:15

+0

如果一个方法返回Void,这意味着它不返回任何东西,那么为什么不反转逻辑并检查可能返回的内容?只是一个想法... – 2009-11-30 14:56:35

+2

编译器说:“System.Void不能从C#使用 - 使用typeof(void)来获得void类型”。啊,只是读错误。 DOH! – 2009-11-30 15:00:07

回答

53

不能直接使用System.Void,但可以使用typeof(void)访问它。

几个人指出(here和评论here为例),对于这种情况的原因是,ECMA Standard 335,分区II,第9.4节说:

The following kinds of type cannot be used as arguments in instantiations (of generic types or methods):

  • Byref types (e.g., System.Generic.Collection.List 1<string&> is invalid)
  • Value types that contain fields that can point into the CIL evaluation stack (e.g., List<System.RuntimeArgumentHandle>)
  • void (e.g., List<System.Void> is invalid)
+14

我这样一个白痴。错误消息显示“使用typeof(void)”。 – 2009-11-30 15:01:00

+2

不再隐藏错误窗口! ;)但它非常奇怪。 – 2009-11-30 15:08:27

18

当我建立这个,我得到的错误:

System.Void cannot be used from C# -- use typeof(void) to get the void type object

听起来好像这就是答案......

+0

是的,我失败了。本来会接受RTFM的回答:) – 2009-11-30 15:03:22