代码之家  ›  专栏  ›  技术社区  ›  Patrik Hägne

参考参数和反射

  •  36
  • Patrik Hägne  · 技术社区  · 16 年前

    ArgumentInfo有一个属性“IsOut”,但没有“IsRef”。如何获取给定MethodInfo中的所有引用参数?

    5 回复  |  直到 16 年前
        1
  •  38
  •   Rex M    16 年前
    ParameterInfo[] parameters = myMethodInfo.GetParameters();
    foreach(ParameterInfo parameter in parameters)
    {
        bool isRef = parameterInfo.ParameterType.IsByRef;
    }
    
        2
  •  9
  •   RobSiklos    10 年前

    ParameterType.IsByRef true 对两者 ref out 参数。

    ParameterInfo MethodInfo.GetParameters()

    • 参数为 如果 parameterInfo.ParameterType.IsByRef && parameterInfo.IsOut
    • 参数为 如果 parameterInfo.ParameterType.IsByRef && parameterInfo.IsOut == false

    IsByRef 检查 参数,那么您将错误地获得用 [Out] System.Runtime.InteropServices 但实际上不是C# 参数。

        3
  •  7
  •   Christian Rodemeyer    16 年前

    void Foo(ref int bar)
    

    那么参数的名称就不会是 int Int32 Int32& 对于每种类型,都有一个对应的ref类型,其中原始类型的后缀为“&'. 你可以通过 IsByRef Type

        4
  •  1
  •   Michel Abi Raad    13 年前

    参数信息。参数类型。如果参数的声明使用ByRef关键字,则IsByRef返回true,如果声明使用ByVal关键字,则返回false(无论参数的类型是按值(例如结构)还是按引用(例如类))。

    为了说明,考虑以下结构和类(我使用VB代码):

    ' Empty structure and class, just for illustration.
    Public Structure MyStruct
    End Structure
    
    Public Class MyClass1
    End Class
    

    Public Sub P(s1 As MyStruct, ByRef s2 As MyStruct, c1 As MyClass1, ByRef c2 As MyClass1)
    End Sub
    

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
          ' Reflect on method P:
        Dim mi As MethodInfo = Me.GetType.GetMethod("P")
       ' Iterate all parameters, and call its ParameterType.IsByRef method:
        For Each pi As ParameterInfo In mi.GetParameters
           If **pi.ParameterType.IsByRef** _
           Then Console.WriteLine(pi.Name & " is ByRef") _
           Else Console.WriteLine(pi.Name & " is ByVal")
        Next
    End Sub
    

    您将得到以下输出:

    s1 is ByVal
    s2 is ByRef
    c1 is ByVal
    c2 is ByRef
    

        5
  •  0
  •   Turbofish    9 年前

    如果ref是 parameterInfo.IsIn == true && parameterInfo.IsOut == true parameterInfo.ParameterType.IsByRef 根本