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

贡献者指南