我在 .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 System
和 using System.Runtime
这两个命名空间
最佳答案
是的,它们在 .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);
}
}
关于c# - .Net Core 中缺少 IsGenericType 和 IsValueType 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39169231/