抛出异常通常遵循以下模式:
if(condition) { throw exception; }
您检查条件,如果满足条件,则抛出异常。那么,我想知道是否推荐编写一个静态类来实现这个功能,代码可能如下:
public static class Throw
{
public static void IfNullOrEmpty<T>(string @string, params object[] parameters) where T : Exception
{
Throw.If<T>(string.IsNullOrEmpty(@string), parameters);
}
public static void IfNullOrEmpty<T, I>(IEnumerable<I> enumerable, params object[] parameters) where T : Exception
{
Throw.If<T>(enumerable == null || enumerable.Count() == 0, parameters);
}
public static void IfNullOrEmpty(string @string, string argumentName)
{
Throw.IfNullOrEmpty(@string, argumentName,
string.Format("Argument '{0}' cannot be null or empty.", argumentName));
}
public static void IfNullOrEmpty(string @string, string argumentName, string message)
{
Throw.IfNullOrEmpty<ArgumentNullOrEmptyException>(@string, message, argumentName);
}
public static void IfNullOrEmpty<I>(IEnumerable<I> enumerable, string argumentName)
{
Throw.IfNullOrEmpty(enumerable, argumentName,
string.Format("Argument '{0}' cannot be null or empty.", argumentName));
}
public static void IfNullOrEmpty<I>(IEnumerable<I> enumerable, string argumentName, string message)
{
Throw.IfNullOrEmpty<ArgumentNullOrEmptyException, I>(enumerable, message, argumentName);
}
public static void IfNull<T>(object @object, params object[] parameters) where T : Exception
{
Throw.If<T>(@object == null, parameters);
}
public static void If<T>(bool condition, params object[] parameters) where T : Exception
{
if (condition)
{
var types = new List<Type>();
var args = new List<object>();
foreach (object p in parameters ?? Enumerable.Empty<object>())
{
types.Add(p.GetType());
args.Add(p);
}
var constructor = typeof(T).GetConstructor(types.ToArray());
var exception = constructor.Invoke(args.ToArray()) as T;
throw exception;
}
}
public static void IfNull(object @object, string argumentName)
{
Throw.IfNull<ArgumentNullException>(@object, argumentName);
}
}
(注:这里未定义
ArgumentNullOrEmptyException
,但它基本上做了人们所期望的事情。)因此,不要反复编写这样的内容。
void SomeFunction(string someParameter)
{
if(string.IsNullOrEmpty(someParameter))
{
throw new ArgumentNullOrEmptyException("someParameter", "Argument 'someParameter' cannot be null or empty.");
}
}
我只是做
void SomeFunction(string someParameter)
{
Throw.IfNullOrEmpty(someParameter, "someParameter"); // not .IsNullOrEmpty
}
我其实喜欢它,但这是否也是一个好的做法呢?
Throw
类的价值,类似于您编写的类。 - Steven Wexler