简体   繁体   中英

Convert c# by-reference type to the matching non-by-reference type

I examine the parameters of a C# method using reflection. The method has some out parameters and for these I get back types, which have IsByRef=true. For example if the parameter is declared as "out string xxx", the parameter has type System.String&. Is there a way to convert System.String& back to System.String? The solution should of course not only work for System.String but for any type.

Use Type.GetElementType() .

Demo:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM