c# - .Net Core 中缺少 IsGenericType 和 IsValueType 吗?

标签 c# asp.net-core .net-core coreclr

我在 .Net 4.6.2 中有此代码,现在尝试转换为 .Net 核心,但出现错误

Error CS1061 'Type' does not contain a definition for 'IsGenericType' and no extension method 'IsGenericType' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

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

.Net Core 中的等价物是什么?

更新1

令人惊讶的是,当我调试代码时,我看到变量 t 具有 IsGenericType 属性,但是我无法在代码中使用 IsGenericType。不确定我需要添加的原因或 namespace 。我添加了 using Systemusing System.Runtime 这两个命名空间

enter image description here

最佳答案

是的,它们在 .Net Core 中被移动到一个新的 TypeInfo 类。实现此功能的方法是使用 GetTypeInfo().IsGenericTypeGetTypeInfo().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);
    }
}

关于c# - .Net Core 中缺少 IsGenericType 和 IsValueType 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39169231/

相关文章:

c# - 如何在类似颠覆的系统中更好地并发处理命令?

c# - SynchronizationContext - 奇怪的行为

c# - Socket.Bind 和 Connect 使用本地地址

c# - 传递到 ViewDataDictionary 的模型项的类型为 'System.ValueTuple` 2

c# - 类型加载异常 : Could not load type IHttpResponseStreamWriterFactory from assembly

c# - 如何在类库中访问 JWT User.Claims

c# - 带有滚动背景图像的 ListView

asp.net-web-api - 使用 Asp.Net Core Web API 进行授权

c# - .Net 核心 HttpClient 错误?套接字异常 : An existing connection was forcibly closed by the remote host

c# - 如何在 ASP .NET Core 中生成和管理 API key