Browse Source

Refactor property conversion logic to TypeHelper

Moved the primitive type conversion logic from HasExtraPropertiesExtensions.GetProperty<TProperty> to a new TypeHelper.ChangeTypePrimitiveExtended<TProperty> method. This centralizes and simplifies type conversion, improving code maintainability and reuse.
pull/23619/head
Halil İbrahim Kalkan 5 months ago
parent
commit
c4372db973
  1. 31
      framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs
  2. 31
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs

31
framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs

@ -80,6 +80,37 @@ public static class TypeHelper
return false;
}
public static TProperty? ChangeTypePrimitiveExtended<TProperty>(object? value)
{
if (value == null)
{
return default;
}
if (IsPrimitiveExtended(typeof(TProperty), includeEnums: true))
{
var conversionType = typeof(TProperty);
if (IsNullable(conversionType))
{
conversionType = conversionType.GetFirstGenericArgumentIfNullable();
}
if (conversionType == typeof(Guid))
{
return (TProperty)TypeDescriptor.GetConverter(conversionType).ConvertFromInvariantString(value.ToString()!)!;
}
if (conversionType.IsEnum)
{
return (TProperty)Enum.Parse(conversionType, value.ToString()!);
}
return (TProperty)Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
}
throw new AbpException("ChangeTypePrimitiveExtended<TProperty> does not support non-primitive types. Use non-generic GetProperty method and handle type casting manually.");
}
public static bool IsNullable(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);

31
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs

@ -26,34 +26,9 @@ public static class HasExtraPropertiesExtensions
public static TProperty? GetProperty<TProperty>(this IHasExtraProperties source, string name, TProperty? defaultValue = default)
{
var value = source.GetProperty(name);
if (value == null)
{
return defaultValue;
}
if (TypeHelper.IsPrimitiveExtended(typeof(TProperty), includeEnums: true))
{
var conversionType = typeof(TProperty);
if (TypeHelper.IsNullable(conversionType))
{
conversionType = conversionType.GetFirstGenericArgumentIfNullable();
}
if (conversionType == typeof(Guid))
{
return (TProperty)TypeDescriptor.GetConverter(conversionType).ConvertFromInvariantString(value.ToString()!)!;
}
if (conversionType.IsEnum)
{
return (TProperty)Enum.Parse(conversionType, value.ToString()!);
}
return (TProperty)Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
}
throw new AbpException("GetProperty<TProperty> does not support non-primitive types. Use non-generic GetProperty method and handle type casting manually.");
return TypeHelper.ChangeTypePrimitiveExtended<TProperty>(
source.GetProperty(name, (object?) defaultValue)
) ?? defaultValue;
}
public static TSource SetProperty<TSource>(

Loading…
Cancel
Save