假设所有相关的类都直接派生自BaseException
它并且在同一个程序集中,您可以使用以下代码:
var exceptionType =
typeof(BaseException)
.Assembly.GetTypes()
.Where(x => x.BaseType == typeof(BaseException))
.Select(x => new { ExceptionType = x, Property = x.GetProperty("ErrorBitNumber", BindingFlags.Public | BindingFlags.Static) })
.Where(x => x.Property != null)
.FirstOrDefault(x => x.Property.GetValue(null, null) == errorBitNumber)
.ExceptionType;
if(exceptionType == null)
throw new InvalidOperationException("No matching exception has been found");
var exception = (BaseException)Activator.CreateInstance(exceptionType);
throw exception;
这应该可行,但我永远不会使用它。我将创建某种异常注册表,可用于检索特定错误位的异常的新实例。
异常注册表可以通过多种方式实现,主要取决于您的确切需求。最通用和最灵活的方法是简单地注册工厂:
public class ExceptionRegistry<TKey, TExceptionBase> where TExceptionBase : Exception
{
private readonly Dictionary<TKey, Func<TExceptionBase>> _factories = new ...;
public void Register(TKey key, Func<TExceptionBase> factory)
{
_factories[key] = factory;
}
public TExceptionBase GetInstance(TKey key)
{
Func<TExceptionBase> factory;
if(!_factories.TryGetValue(key, out factory))
throw new InvalidOperationException("No matching factory has been found");
return factory();
}
}
用法是这样的:
var exception = registry.GetInstance(errorBitNumber);
throw exception;
因为它是最灵活的方法,所以在实际注册异常类方面也是最冗长的方法:
var registry = new ExceptionRegistry<int, BaseException>();
registry.Register(ExceptionOne.ErrorBitNumber, () => new ExceptionOne());
registry.Register(ExceptionTwo.ErrorBitNumber, () => new ExceptionTwo());
registry.Register(ExceptionThree.ErrorBitNumber, () => new ExceptionThree());
您基本上必须手动注册每个异常类。但是,这样做的好处是您可以自定义异常的创建:
registry.Register(ExceptionFour.ErrorBitNumber,
() => new ExceptionFour(some, parameters));
如果您不想为每个异常类创建手动注册,您可以结合这两种方法:
您仍将使用反射来获取所有异常类。但结果将用于填充注册表,以便您可以使用注册表实际检索实例。以这种方式使用反射来创建注册表基本上是“约定优于配置”。这里最大的优势是您只执行一次注册,基本上成为基础设施代码。之后,你就有了一个定义明确的接口——注册表——你可以使用。
它可能看起来像这样:
var registry = new ExceptionRegistry<int, BaseException>();
var exceptions =
typeof(BaseException)
.Assembly.GetTypes()
.Where(x => x.BaseType == typeof(BaseException))
.Select(x => new { ExceptionType = x, Property = x.GetProperty("ErrorBitNumber", BindingFlags.Public | BindingFlags.Static) })
.Where(x => x.Property != null)
.Select(x => new { Key = (int)x.Property.GetValue(null, null)
Factory = (Func<BaseException>)(() => Activator.CreateInstance(x.ExceptionType)) });
foreach(var exception in exceptions)
registry.Register(exception.Key, exception.Factory);
实际获取异常实例的用法将使用注册表:
var exception = registry.GetInstance(errorBitNumber);
throw exception;