【问题标题】:Why does typeof(T).IsEnum return true, even though the documentation says it should always return false?为什么 typeof(T).IsEnum 返回 true,尽管文档说它应该总是返回 false?
【发布时间】:2012-09-15 14:04:00
【问题描述】:

在尝试回答这个问题时出现了这个问题:

https://stackoverflow.com/questions/12434634

the Type.IsEnum property 的文档说:

如果当前 Type 表示泛型类型或泛型方法定义中的类型参数,则该属性始终返回 false。

但我没有看到这种行为。 typeof(T).IsEnum 正在返回 true。为什么?我是否误解了文档?

示例代码:

using System;

static class Program
{
    public static void Test<TEnum>() where TEnum : struct
    {
        Console.WriteLine(typeof(TEnum).IsEnum);
    }

    public static void Test<TEnum>(this string text) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum)
        {
            Console.WriteLine("Not an enum");
            return;
        }

        Console.WriteLine("Is an enum");
    }

    public enum Test1
    {
        Value1,
        Value2,
    }

    public enum Test2 : byte
    {
        Value3,
        Value4,
    }

    static void Main(string[] args)
    {
        Test<Test1>();
        Test<Test2>();
        "".Test<Test1>();
        "".Test<Test2>();
    }
}

我得到的结果是:

正确
真的
是一个枚举
是一个枚举

看完the documentation for the Type.IsEnum property,我预计结果是:

错误
假的
不是枚举
不是枚举

【问题讨论】:

    标签: c# enums


    【解决方案1】:

    文档正在讨论表示开放泛型类型或方法的类型参数的类型对象。在您的代码中,您正在查询表示封闭泛型方法中类型参数的类型对象,并且在您的示例中,该类型参数当然 枚举类型。

    换句话说,该文档正在讨论通过在 typeof(List&lt;&gt;) 上调用 GetGenericArguments 获得的类型,而不是在 typeof(List&lt;SomeEnum&gt; 上)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多