DD.WellWorkover.Cloud/AsbCloudWebApi.Tests/ReflectionExtensions.cs

48 lines
1.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Tests
{
public static class ReflectionExtensions
{
private static readonly Dictionary<Type, object> _commonTypeDictionary = new()
{
{ typeof(int), default(int) },
{ typeof(Guid), default(Guid) },
{ typeof(DateOnly), default(DateOnly) },
{ typeof(DateTime), default(DateTime) },
{ typeof(DateTimeOffset), default(DateTimeOffset) },
{ typeof(TimeOnly), default(TimeOnly) },
{ typeof(long), default(long) },
{ typeof(bool), default(bool) },
{ typeof(double), default(double) },
{ typeof(short), default(short) },
{ typeof(float), default(float) },
{ typeof(byte), default(byte) },
{ typeof(char), default(char) },
{ typeof(uint), default(uint) },
{ typeof(ushort), default(ushort) },
{ typeof(ulong), default(ulong) },
{ typeof(sbyte), default(sbyte) }
};
public static object? GetDefaultValue(this Type type)
{
if (!type.IsValueType)
{
return null;
}
return _commonTypeDictionary.TryGetValue(type, out var value)
? value
: Activator.CreateInstance(type);
}
public static bool IsDefaultValue(this Type type, object? value)
=> (value?.Equals(type.GetDefaultValue()) != false);
}
}