c# - dotnetcore GetTypeInfo() 没有在类型对象的变量上定义?

标签 c# .net-core

下面的代码是演示问题的原始代码的精简版本。在 dotnetcore (1.0.1) 中,.IsEnum 属性被移动到 System.Reflection。我进行了所有按预期工作的更改。但是,我无法使用的是对象类型。

编译器抛出这个错误: c:\tmp\netcore\repro\Program.cs(14,17): error CS0103: 当前上下文中不存在名称“t”

public class Program
{
    enum Kleur {Red, Blue, Green}

    public static void Main(string[] args)
    {
        object myType = Kleur.Green;
        if (myType.GetTypeInfo().IsEnum)
        {
            Console.WriteLine("Yes its an enum");
        }
    }
}

在 dotnetcore 中是否有测试对象是否为 Enum 类型的变通方法?是否有特定原因导致类型对象没有扩展方法(我需要的所有其他类型似乎都可以工作)。

最佳答案

当从 Type 移动到 TypeInfo 时,.GetType() 的替换不仅仅是 .GetTypeInfo(),它是 .GetType().GetTypeInfo()。那是因为 Type 没有被删除,而是被拆分为 Type,它只包含一些基本成员,而 TypeInfo 则包含其余部分。

所以,你的代码应该是:

object myType = Kleur.Green;
if (myType.GetType().GetTypeInfo().IsEnum)
{
    Console.WriteLine("Yes its an enum");
}

关于c# - dotnetcore GetTypeInfo() 没有在类型对象的变量上定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39642578/

相关文章:

c# - 将 RTF 直接读取到 Android 上的 TextView

c# - Windows 窗体 - mac - xamarin

c# - conditional-middleware-in-aspnet-core 在 asp.net core 1.1 中不工作

c# - react +ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource

c# - Entity Framework Core linq 查询返回 InvalidCastException

c# - _userManager.GetUserAsync(User) 返回 null

c# - TPL 数据流 : Persist previous data

c# - #if DEBUG 和 return 语句 - 无法访问的代码警告

c# - 为什么在实现隐式转换时 C# 记录会产生不同的 Linq 表达式?

c# - Microsoft.EntityFrameworkCore.Tools - Azure Functions 与 .NET 5(独立)使用 HostBuilder 创 build 计时 DbContext