【发布时间】:2020-01-22 03:44:24
【问题描述】:
我有以下场景:
- 我有几个实现基本异常的派生异常类
//Base exception type
public class SaberpsicologiaException : Exception
{
}
//One of the derived exception class
public class MovedPermanentlyException : SaberpsicologiaException
{
public string CannonicalUri { get; private set; }
public MovedPermanentlyException(string cannonicalUri)
: base($"Moved permanently to {cannonicalUri}")
{
this.CannonicalUri = cannonicalUri;
}
}
- 对于每个异常类,我想实现一个异常处理程序,它将返回一个 ActionResult,它将实现一个通用接口:
interface ISaberpsicologiaExceptionHandler<T>
where T : SaberpsicologiaException
{
ActionResult Result(T exception);
}
public class MovedPermanentlyExceptionHandler
: ISaberpsicologiaExceptionHandler<MovedPermanentlyException>
{
public ActionResult Result(MovedPermanentlyException exception)
{
var redirectResult = new RedirectResult(exception.CannonicalUri);
redirectResult.Permanent = true;
return redirectResult;
}
}
- 当我捕获从 SaberpsicologiaException 派生的异常时,我希望相应的处理程序运行:
public class ExceptionHandlerFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
HandleResponseCodeByExceptionType(context);
}
private void HandleResponseCodeByExceptionType(ExceptionContext context)
{
var exception = context.Exception;
if (!CanHandle(exception))
{
return;
}
var mapping = new Dictionary<Type, Type>
{
{ typeof(MovedPermanentlyException), typeof(MovedPermanentlyExceptionHandler) }
};
var handlerType = mapping[exception.GetType()];
var handler = Activator.CreateInstance(handlerType);
handler.Result(exception); //<- compilation error
//handler is type "object" and not MovedPermanentlyExceptionHandler
}
}
我尝试使用 Activator (Reflection) 来解决它,但我遇到了没有真正具有 ISaberpsicologiaExceptionHandler 类型的对象的问题,因此我无法正确使用该类型。
总而言之,问题是我有一个异常类型,我想获取该异常类型的 ISaberpsicologiaExceptionHandler,我想我可以使用更多反射来执行“结果”方法,但我想这样做优雅一点。
【问题讨论】:
-
Activator.CreateInstance返回object。您缺少例如MovedPermanentlyExceptionHandler:var handler = Activator.CreateInstance(handlerType) as MovedPermanentlyExceptionHandler; -
我不能使用通用版本,因为我不知道它是哪种类型,在编译时(我知道我什至不需要使用激活器)
标签: c# generics reflection concrete