.Net Core中缺少IsGenericType和IsValueType?

LP1*_*P13 23 c# .net-core coreclr asp.net-core

我在.Net 4.6.2中有这个代码,现在尝试转换为.Net核心但是我收到了错误

错误CS1061'Type'不包含'IsGenericType'的定义,也没有扩展方法'IsGenericType'接受类型'Type'的第一个参数(你是否缺少using指令或汇编引用?)

public static class StringExtensions
{
    public static TDest ConvertStringTo<TDest>(this string src)
    {
        if (src == null)
        {
            return default(TDest);
        }           

        return ChangeType<TDest>(src);
    }

    private static T ChangeType<T>(string value)
    {
        var t = typeof(T);

        // getting error here at t.IsGenericType
        if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
            {
                return default(T);
            }

            t = Nullable.GetUnderlyingType(t);
        }

        return (T)Convert.ChangeType(value, t);
    }
}
Run Code Online (Sandbox Code Playgroud)

什么相当于.Net Core?

UPDATE1

令人惊讶的是,当我调试代码时,我看到变量tIsGenericType 属性,但我不能IsGenericType在代码中使用.不确定我需要添加的原因或名称空间.我已经加入using Systemusing System.Runtime两个命名空间

在此输入图像描述

Ven*_*nky 36

是的,他们被.Net Core转移到一个新TypeInfo类.实现这一目标的方法是使用GetTypeInfo().IsGenericType&GetTypeInfo().IsValueType.

using System.Reflection;

public static class StringExtensions
{
    public static TDest ConvertStringTo<TDest>(this string src)
    {
        if (src == null)
        {
            return default(TDest);
        }           

        return ChangeType<TDest>(src);
    }

    private static T ChangeType<T>(string value)
    {
        var t = typeof(T);

        // changed t.IsGenericType to t.GetTypeInfo().IsGenericType
        if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
            {
                return default(T);
            }

            t = Nullable.GetUnderlyingType(t);
        }

        return (T)Convert.ChangeType(value, t);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不知道你为什么问我,但是,它在`System.Reflection`中. (6认同)
  • @svick在其他名称空间中是`GetTypeInfo()`扩展方法?intelisense无法找到它 (2认同)