ant-design-blazor/components/core/Helpers/THelper.cs

94 lines
2.6 KiB
C#
Raw Normal View History

// 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)
{
return ChangeType<T>(value, null);
}
public static T ChangeType<T>(object value, IFormatProvider provider)
{
var t = typeof(T);
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return default(T);
}
t = Nullable.GetUnderlyingType(t);
}
if (provider == null) return (T)Convert.ChangeType(value, t);
return (T)Convert.ChangeType(value, t, provider);
}
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;
}
}
}