2021-04-11 01:11:19 +08:00
|
|
|
|
// Licensed to the .NET Foundation under one or more agreements.
|
|
|
|
|
// The .NET Foundation licenses this file to you under the MIT license.
|
|
|
|
|
// See the LICENSE file in the project root for more information.
|
|
|
|
|
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace AntDesign
|
|
|
|
|
{
|
|
|
|
|
public static class THelper
|
|
|
|
|
{
|
|
|
|
|
public static T ChangeType<T>(object value)
|
2021-05-06 13:00:16 +08:00
|
|
|
|
{
|
|
|
|
|
return ChangeType<T>(value, null);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static T ChangeType<T>(object value, IFormatProvider provider)
|
2021-04-11 01:11:19 +08:00
|
|
|
|
{
|
|
|
|
|
var t = typeof(T);
|
|
|
|
|
|
|
|
|
|
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
|
|
|
|
|
{
|
|
|
|
|
if (value == null)
|
|
|
|
|
{
|
|
|
|
|
return default(T);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
t = Nullable.GetUnderlyingType(t);
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-06 13:00:16 +08:00
|
|
|
|
if (provider == null) return (T)Convert.ChangeType(value, t);
|
|
|
|
|
return (T)Convert.ChangeType(value, t, provider);
|
2021-04-11 01:11:19 +08:00
|
|
|
|
}
|
2021-05-06 13:00:16 +08:00
|
|
|
|
|
2021-04-11 01:11:19 +08:00
|
|
|
|
public static bool IsTypeNullable<T>()
|
|
|
|
|
{
|
|
|
|
|
return Nullable.GetUnderlyingType(typeof(T)) != null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static Type GetNullableType<T>()
|
|
|
|
|
{
|
|
|
|
|
Type type = typeof(T);
|
|
|
|
|
type = Nullable.GetUnderlyingType(type) ?? type;
|
|
|
|
|
if (type.IsValueType)
|
|
|
|
|
return typeof(Nullable<>).MakeGenericType(type);
|
|
|
|
|
else
|
|
|
|
|
return type;
|
|
|
|
|
}
|
|
|
|
|
public static Type GetUnderlyingType<T>()
|
|
|
|
|
{
|
|
|
|
|
Type type = typeof(T);
|
|
|
|
|
Type targetType;
|
|
|
|
|
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
|
|
|
|
|
{
|
|
|
|
|
targetType = Nullable.GetUnderlyingType(type);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
targetType = type;
|
|
|
|
|
}
|
|
|
|
|
return targetType;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static bool IsNumericType<T>()
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
Type type = GetUnderlyingType<T>();
|
|
|
|
|
if (type == null)
|
|
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
switch (Type.GetTypeCode(type))
|
|
|
|
|
{
|
|
|
|
|
case TypeCode.Byte:
|
|
|
|
|
case TypeCode.Decimal:
|
|
|
|
|
case TypeCode.Double:
|
|
|
|
|
case TypeCode.Int16:
|
|
|
|
|
case TypeCode.Int32:
|
|
|
|
|
case TypeCode.Int64:
|
|
|
|
|
case TypeCode.SByte:
|
|
|
|
|
case TypeCode.Single:
|
|
|
|
|
case TypeCode.UInt16:
|
|
|
|
|
case TypeCode.UInt32:
|
|
|
|
|
case TypeCode.UInt64:
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|