【发布时间】:2019-08-26 08:24:17
【问题描述】:
我正在尝试创建一个自动映射器辅助函数来检查枚举的转换(我在映射器中自定义了业务逻辑)
mapper 是一个实例,非静态的。
var cfgExp = new MapperConfigurationExpression();
cfgExp.AddProfile<ProfileXXX>()
MapperConfiguration mapConfig = new MapperConfiguration(cfgExp);
IMapper mapper = new Mapper(mapConfig);
mapper.ConfigurationProvider.AssertConfigurationIsValid();
mapper.AssertEnumConversion(cfgExp);
public static void AssertEnumConversion(this IMapper @thisMapper, MapperConfigurationExpression cfgExp)
{
try
{
if (@thisMapper == null)
throw new ArgumentNullException(nameof(@thisMapper));
List<TypePair> enumMapping = cfgExp
.Profiles
.SelectMany(x => x.TypeMapConfigs)
.Where(x => x.Types.SourceType.IsEnum)
.Select(x => x.Types)
.ToList();
MethodInfo methodMap = @thisMapper
.GetType()
.GetMethods()
.Where(x => x.Name == "Map" && x.IsGenericMethod)
.ToList()[0];//here i've seen 6 mappers take first //TDestination Map<TDestination>(object source)
foreach (var item in enumMapping)
{
Type tSource = item.SourceType;
Type tDest = item.DestinationType;
//here i've an helper to take a ienumerable<Enum>
MethodInfo method = typeof(EnumConverters).GetMethod("GetEnumValues");
MethodInfo methodGenericSource = method.MakeGenericMethod(tSource);
object enumsSource = methodGenericSource.Invoke(null, null);
IEnumerable<int> enumIenumInt = enumsSource as IEnumerable<int>;
if (enumIenumInt == null)
throw new ApplicationException($"enumIenumInt==null ({tSource.FullName} to {tDest.FullName})");
Array enumArray = Array.CreateInstance(tDest, enumIenumInt.Count());
foreach (var e in enumArray)
{
MethodInfo methodMapGeneric = methodMap.MakeGenericMethod(tDest);
//here i've exeption invoking...
methodMapGeneric.Invoke(@thisMapper, new object[1] { e });
}
}
}
catch (Exception e)
{
throw;
}
但我收到异常,例如映射器未初始化... 我哪里错了!?!?
【问题讨论】:
-
抛出了哪一行,exact 错误是什么?
-
@nvoigt methodMapGeneric.Invoke(@thisMapper, new object[1] { e });
-
您要检查的究竟是什么?如果给定一个特定的输入枚举
A正确的值B得到结果? -
这不是这样做的方法。检查this。
-
@LucianBargaoanu 我已经在映射中做到了。现在我想要在默认 AssertConfigurationIsValid 之后有一个自定义断言
标签: .net reflection enums automapper