将c#by-reference类型转换为匹配的非引用类型

Ach*_*him 15 c# reflection

我使用反射检查C#方法的参数.该方法有一些输出参数,对于这些参数,我得到了返回类型,它们具有IsByRef = true.例如,如果参数声明为"out string xxx",则参数的类型为System.String&.有没有办法将System.String转换回System.String?解决方案当然不仅适用于System.String,也适用于任何类型.

Jon*_*eet 26

使用Type.GetElementType().

演示:

using System;
using System.Reflection;

class Test
{
    public void Foo(ref string x)
    {
    }

    static void Main()
    {
        MethodInfo method = typeof(Test).GetMethod("Foo");
        Type stringByRef = method.GetParameters()[0].ParameterType;
        Console.WriteLine(stringByRef);
        Type normalString = stringByRef.GetElementType();
        Console.WriteLine(normalString);        
    }
}
Run Code Online (Sandbox Code Playgroud)