【问题标题】:In C#, Relfection incorrectly determines IsGenericType property for ByRef method argument在 C# 中,Relfection 错误地确定了 ByRef 方法参数的 IsGenericType 属性
【发布时间】:2020-04-08 15:32:30
【问题描述】:

谁能解释一下为什么我看到了我所看到的(下面的控制台截图)?对于“ref”和非“ref”方法参数,我从 Reflection 获得了不同的泛型相关属性。我正在使用 .NET 4.8(经典的 .NET Framework)。

public class MyClass {

    public class Aref
    {
        public virtual void method(object je, ref List<MyClass> batchlist, object doc)
        {
        }
    }


    public class A
    {
        public virtual void method(object je, List<MyClass> batchlist, object doc)
        {
        }
    }

    private static void WriteGenericProps(Type type)
    {
        var method = type.GetMethod(nameof(Aref.method));
        var param = method.GetParameters().First(p => p.Name == "batchlist");

        Console.WriteLine(nameof(param.ParameterType.IsByRef) + "=" + param.ParameterType.IsByRef);
        Console.WriteLine(nameof(param.ParameterType.IsGenericType) + "=" + param.ParameterType.IsGenericType);
        Console.WriteLine(nameof(param.ParameterType.ContainsGenericParameters) + "=" + param.ParameterType.ContainsGenericParameters);
        Console.WriteLine(nameof(param.ParameterType.IsConstructedGenericType) + "=" + param.ParameterType.IsConstructedGenericType);
        Console.WriteLine(nameof(param.ParameterType.IsGenericParameter) + "=" + param.ParameterType.IsGenericParameter);
        Console.WriteLine(nameof(param.ParameterType.IsGenericTypeDefinition) + "=" + param.ParameterType.IsGenericTypeDefinition);
    }

    static void Main(string[] args)
    {
        var t = typeof(Aref);
        Console.WriteLine(t.Name);
        WriteGenericProps(t);
        Console.WriteLine();

        t = typeof(A);
        Console.WriteLine(t.Name);
        WriteGenericProps(t);
    }
}

【问题讨论】:

    标签: c# .net generics reflection


    【解决方案1】:

    正如RemarksIsGenericType 所说:

    如果直接类型不是泛型,IsGenericType 属性将返回 false。例如,元素类型为 A&lt;int&gt;(Visual Basic 中为 A(Of Integer))的数组本身不是泛型类型。

    如果batchlistList&lt;MyClass&gt;[] 或指针,您会发现得到相同的结果。

    如果你有一个 by-ref 类型,你需要调用GetElementType() 来获取底层类型。这会为您提供typeof(List&lt;MyClass&gt;),其行为与您预期的一样。

    【讨论】:

    • 在发布之前,我阅读了您所指的备注部分。但我还是不明白。 List&lt;MyClass&gt; batchlist 既不是数组也不是指针。或者在这种情况下,by-ref 是否意味着“指针”,因为幕后实际发生的是将“指针”传递给方法的原始引用?
    • By-ref 的意思是“有ref”。您正在查看的 Type 对象代表 ref &lt;Thing&gt;。您需要调用GetElementType() 来获取&lt;Thing&gt; 的Type 对象。
    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 2017-04-12
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多