C# 为什么用于枚举到类转换的自定义成员解析程序不工作?
我收到异常消息: 未为“NotificationArea”和“System.Object”类型定义二进制运算符NotEqual 源枚举:C# 为什么用于枚举到类转换的自定义成员解析程序不工作?,c#,asp.net-web-api,automapper,C#,Asp.net Web Api,Automapper,我收到异常消息: 未为“NotificationArea”和“System.Object”类型定义二进制运算符NotEqual 源枚举: public enum NotificationArea { One, Two, Three } 目的地类别: public class EnumValue { public EnumValue() { } public EnumValue(Enum tEnum) { Id =
public enum NotificationArea
{
One,
Two,
Three
}
目的地类别:
public class EnumValue
{
public EnumValue()
{
}
public EnumValue(Enum tEnum)
{
Id = Convert.ToInt32(tEnum);
Name = GetEnumValue(tEnum, tEnum.GetType());
}
public int Id { get; set; }
public string Name { get; set; }
public string GetEnumValue(Enum tEnum, Type type)
{
MemberInfo member = type.GetMember(tEnum.ToString())[0];
if (member.GetCustomAttribute<DisplayAttribute>() != null)
{
DisplayAttribute attribute = member.GetCustomAttribute<DisplayAttribute>();
return attribute.Name;
}
return tEnum.ToString();
}
}
public class EnumConverter : IMemberValueResolver<Notification,
NotificationModel, NotificationArea, EnumValue>
{
public EnumValue Resolve(Notification source, NotificationModel destination,
NotificationArea sourceMember, EnumValue destMember, ResolutionContext context)
{
var model = source.Area.ToDisplay();
return model;
}
}
实施:
// Query
var notifications = await _db.Notifications
.OrderByDescending(x => x.Timestamp)
.ProjectTo<NotificationModel>(_mapperConfig)
.ToListAsync(token);
// Mapping
CreateMap<Notification, NotificationModel>()
.ForMember(dest => dest.Area, opt => opt.ResolveUsing(src => src.Area));
我知道我做错了什么。。。明显地我只是不知道它到底在哪里。我觉得我有A和C,但缺少B。哇,代码太多了!我对您的EnumValue类很感兴趣,您需要花费大量的精力来做一些事情(例如,您可以调用
MemberInfo.GetCustomAttribute
,但您的代码中没有[Display]
)。你看过System.Enum类了吗?它免费完成了该类的大部分工作(据我所知)。您显示了错误消息,但没有说明它发生在哪里。代码之间有一些文本,但从未解释过要做什么。你能更清楚地说明你的目的吗?@Flydog57这是正确的,不在这个代码示例中。这只是检查显示属性是否存在。此错误在运行时出现。当然最终目标是将NotificationModel作为JSON传递,EnumValue将具有Enum的属性,但可分配给JavaScript变量。LucianBargaoanu我刚刚通读了这一点和相关问题;我认为我的问题不同。
// Query
var notifications = await _db.Notifications
.OrderByDescending(x => x.Timestamp)
.ProjectTo<NotificationModel>(_mapperConfig)
.ToListAsync(token);
// Mapping
CreateMap<Notification, NotificationModel>()
.ForMember(dest => dest.Area, opt => opt.ResolveUsing(src => src.Area));
public class Notification
{
public int Id {get;set;}
public NotificationArea Area { get; set; }
}
public class NotificationModel
{
public int Id {get;set;}
public EnumValue Area {get;set;}
}