增加反射的性能 func<T>

increase performance func<T> for reflection

我目前正在编写一段代码来确定字段的 TypeValue(所有 enum),因此我们可以查找翻译具体枚举。我知道这是一个相当昂贵的,但我没有看到更好的解决方案。谁知道更合适的?

我正在使用自动映射器进行映射..

//removed some code
CreateMap<CarModel, CarDTO>
    .ForMember(dst => dst.CarBodyType, opt => opt.MapFrom((detail, dto, _, context) => ResolveEnumTranslation(detail, context, car => car.CarBodyType)))
    .ForMember(dst => dst.FuelType, opt => opt.MapFrom((detail, dto, _, context) => ResolveEnumTranslation(detail, context, car => car.FuelType)))
    .ForMember(dst => dst.GearType, opt => opt.MapFrom((detail, dto, _, context) => ResolveEnumTranslation(detail, context, car => car.GearType)))
//removed more for clearity (there are more enums)

private string ResolveEnumTranslation(CarDetail carDetail, ResolutionContext context, Func<CarDetail, object> property)
{
    var selectedEnum = property.Invoke(carDetail);

    if (context.Items.TryGetValue(localeKey, out var locale) && locale is string localeString)
    {
        return carDetail.Country.Translations
            .FirstOrDefault(t => t.EnumType == selectedEnum.GetType().Name
                        && t.EnumValue == (int)selectedEnum
                        && string.Equals(t.CountryLocale?.Locale, localeString, StringComparison.OrdinalIgnoreCase))
            ?.TranslatedValue ?? property.Invoke(carDetail).ToString();
    }

    return selectedEnum.ToString();
}

真的很好奇什么是更好的方法。

您可以使方法在 enum 类型上通用,这允许传入 enum 值 as-is。

这允许通过 typeof(T) 检索 enum 类型,它发生在编译时,而 selectedEnum.GetType() 发生在运行时。

您必须分析这是否会提高性能。

C# 7.3 开始,您甚至可以使用通用 Enum 约束来保护 enum 值作为参数传递;例如。 where T : Enum

通过

调用下面的方法
ResolveEnumTranslation(detail, context, car.GearType)

private string ResolveEnumTranslation<T>(
     CarDetail carDetail, ResolutionContext context, T selectedEnum
     ) where T : Enum
{
    var typeName = typeof(T).Name;

    if (context.Items.TryGetValue(localeKey, out var locale) && locale is string localeString)
    {
        return carDetail.Country.Translations
            .FirstOrDefault(t =>
                 t.EnumType == typeName
                 && t.EnumValue == Convert.ToInt32(selectedEnum)
                 && string.Equals(t.CountryLocale?.Locale, localeString, StringComparison.OrdinalIgnoreCase)
            )?.TranslatedValue ?? selectedEnum.ToString();
    }

    return selectedEnum.ToString();
}