【问题标题】:Convert c# by-reference type to the matching non-by-reference type将 c# 引用类型转换为匹配的非引用类型
【发布时间】:2012-02-12 02:34:01
【问题描述】:

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

【问题讨论】:

  • 介意我将标题从“参考”更改为“按参考”吗?

标签: c# reflection


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2010-11-23
    相关资源
    最近更新 更多