【发布时间】:2021-05-08 16:44:41
【问题描述】:
我想创建一个字典来存储异常和该异常的格式化程序。
Dictionary<Type, Func<Exception, ApiErrorResponse>>
我可以像这样直接将它们添加到字典中
Dictionary<Type, Func<Exception, ApiErrorResponse>> _exceptionFormatters =
new Dictionary<Type, Func<Exception, ApiErrorResponse>>
{
{
typeof(ValidationException),
ex =>
{
var e = ex as ValidationException;
return new ApiErrorResponse(HttpStatusCode.UnprocessableEntity, e.Errors);
}
},
{
typeof(NotFoundException),
ex =>
{
var e = ex as NotFoundException;
return new ApiErrorResponse(HttpStatusCode.NotFound, e.Message);
}
}
};
但我想用通用的AddExceptionFormatter 方法来做
public static void AddExceptionFormatter<T>(Func<T, ApiErrorResponse> Value) where T : Exception
{
if (_exceptionFormatters.ContainsKey(typeof(T)))
_exceptionFormatters[typeof(T)] = (Func<Exception, ApiErrorResponse>)Value;
else
_exceptionFormatters.Add(typeof(T), (Func<Exception, ApiErrorResponse>)Value);
}
这是我调用它的方式。
AddExceptionFormatter<NotFoundException>(ex =>
{
return new ApiErrorResponse(
HttpStatusCode.NotFoundException,
nameof(NotFoundException),
ex.Message);
});
但不幸的是,我得到了
Unable to cast object of type 'System.Func`2[NotFoundException,ApiErrorResponse]' to type 'System.Func`2[System.Exception,ApiErrorResponse]'.
有什么想法可以投我的Func<,>吗?
【问题讨论】:
-
使用
TryGetValue而不是ContainsKey。它对您当前的问题没有帮助,但会更快。
标签: c# .net generics type-conversion