dotnet/runtime

Reflection on enums creates instances of open generic types

Open

#7,976 建立於 2017年4月28日

在 GitHub 查看
 (16 留言) (3 反應) (0 負責人)C# (5,445 fork)batch import
area-System.Reflectionbughelp wanted

倉庫指標

Star
 (17,886 star)
PR 合併指標
 (平均合併 12天 11小時) (30 天內合併 661 個 PR)

描述

From https://codeblog.jonskeet.uk/2017/04/26/surprise-creating-an-instance-of-an-open-generic-type/

using System;
using System.Reflection;
 
class Program
{
    static void Main(string[] args)
    {
        object x = GetWeirdValue();
        // This line prints True
        Console.WriteLine(x.GetType().GetTypeInfo().IsGenericTypeDefinition);
    }
 
    static object GetWeirdValue() =>
        typeof(Generic<>.GenericEnum).GetTypeInfo()
            .GetDeclaredField("Foo")
            .GetValue(null);
 
    class Generic<T>
    {
        public enum GenericEnum
        {
            Foo = 0
        }
    }
}

貢獻者指南