我正在一家工厂内工作,该工厂将根据类型返回接口的通用实现。
我的主要问题是
为什么这些typeof(TException)!= exception.GetType()?分别,我必须更改什么才能为TException具有正确的类型?
上面的代码导致InvalidCast异常,因为它尝试强制转换为IDocumedisExceptionHandler<DocumedisException>
而不是IDocumedisExceptionHandler<FhirParsingException>
工厂实施:
internal class DocumedisExceptionHandlerFactory : IDocumedisExceptionHandlerFactory
{
private readonly IDictionary<Type, object> _exceptionHandlers = new ConcurrentDictionary<Type, object>();
public void RegisterExceptionHandler<TException>(IDocumedisExceptionHandler<TException> exceptionHandler)
where TException : DocumedisException
{
_exceptionHandlers.Add(typeof(TException), exceptionHandler);
}
public IDocumedisExceptionHandler<TException> GetDocumedisExceptionHandler<TException>(TException exception)
where TException : DocumedisException
{
_exceptionHandlers.TryGetValue(exception.GetType(), out var exceptionHandler);
return (IDocumedisExceptionHandler<TException>) exceptionHandler;
}
}
附带问题:是否有比object
字典值更好的方法?
在启动程序中注册处理程序:
var exceptionHandlerFactory = app.ApplicationServices.GetService<IDocumedisExceptionHandlerFactory>();
exceptionHandlerFactory.RegisterExceptionHandler(new FhirParsingExceptionHandler());
在哪里FhirParsingExceptionHandler
实施IDocumedisExceptionHandler
internal class FhirParsingExceptionHandler : IDocumedisExceptionHandler<FhirParsingException>
{
public void HandleException(FhirParsingException exception, out HttpStatusCode httpStatusCode, out OperationOutcome.IssueType issueType, out string message)
{
httpStatusCode = HttpStatusCode.BadRequest;
issueType = OperationOutcome.IssueType.Invalid;
message = exception.Message;
}
}
处理程序定义(在哪里TException
相反):
public interface IDocumedisExceptionHandler<in TException>
where TException : DocumedisException
{
void HandleException(TException exception, out HttpStatusCode httpStatusCode, out OperationOutcome.IssueType issueType, out string message);
}
并FhirParsingException
扩展DocumedisException
:
public class FhirParsingException : DocumedisException
{
[...]
}
从中间件检索处理程序:
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
if (ex is DocumedisException documedisException)
{
await HandleDocumedisExceptionAsync(context, documedisException);
}
else
{
throw;
}
}
}
private async Task HandleDocumedisExceptionAsync<TException>(HttpContext context, TException ex, MedicationAnalyzerErrorCode? errorCode = null)
where TException : DocumedisException
{
var exceptionHandler = _documedisExceptionHandlerFactory.GetDocumedisExceptionHandler(ex);
[...]
}
typeof(TException)
为您提供的编译时间类型exception
。exception.GetType()
为您提供的运行时类型exception
。这两个不需要完全相同,编译器所做的唯一保证就是运行时类型exception
可以分配给TException
变量。
考虑以下:
class Animal { }
class Turtle: Animal { }
bool CheckTypes<T>(T animal) where T: Animal
{
return typeof(T) == animal.GetType();
}
现在您有了:
Animal animal = new Turtle();
Feed(animal);
放心,CheckTypes
会退货false
;泛型类型参数的类型为,Animal
但是的运行时类型animal
为Turtle
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句