C#:具有不同泛型类型的多个处理程序

时间:2017-11-13 18:56:00

标签: c# generics

我想基于参数的类型实现一些处理程序逻辑。例如,为WebAPI实现异常过滤器属性:

public class ExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}

这看起来非常好,但我想做的是为不同类型的例外添加几个处理程序,例如: DbEntityValidationException,或我的业务逻辑可能抛出的其他一些自定义异常。

当然,我可以轻松地添加另一个if - 块来检查异常是否是某种类型,但我宁愿避免这种情况,并将不同异常类型的处理分解为单独的类。

此类的接口可能如下所示

public interface ExceptionHandler<T> where T : Exception {
    void Handle(HttpActionExecutedContext context, T exception);
}

我现在想将这些ExceptionHandler的实现添加到ExceptionFilterAttribte的集合中,因此我可以检查是否存在遇到的异常处理程序并执行相应的转换并调用处理程序。但是,我无法弄清楚,我将如何实现此部分,因为我无法将具有不同泛型类型ExceptionHandler的{​​{1}}接口的实现添加到单个集合中(例如T ):

class DbEntityValidationExceptionHandler : ExceptionHandler<DbEntityValidationException>

如何在集合中保留对 private List<ExceptionHandler<Exception>> handlers = new List<ExceptionHandler<Exception>>() { new DbEntityValidationExceptionHandler() // does not compile... }; 接口的不同实现的引用?或者这种方法是否完全被误导,并且有更好的方法来处理这种情况?非常感谢任何建议。

1 个答案:

答案 0 :(得分:2)

您可以使用Variant Generic Interface

执行此操作
class TestException : Exception
{
}
class TestException2:Exception
{
}

class foo : ExceptionHandler<TestException> { }
class bar : ExceptionHandler<TestException2> { }

public interface ExceptionHandler<out T> where T : Exception
{ }

class Program
{
    static void Main(string[] args)
    {
        List<ExceptionHandler<Exception>> a = new List<ExceptionHandler<Exception>>();
        a.Add(new foo());
        a.Add(new bar());
    }

}