往往在架构中throw
随处可见。
throw new ArgumentException($"Input {parameterName} was not in required format", parameterName);
Ardalis.GuardClauses
用来解决这个问题。
<ItemGroup>
<PackageReference Include="Ardalis.GuardClauses" Version="3.0.1" />
</ItemGroup>
用法
public class Order
{
private string _name;
private int _quantity;
private long _max;
private decimal _unitPrice;
private DateTime _dateCreated;
public Order(string name, int quantity, long max, decimal unitPrice, DateTime dateCreated)
{
_name = Guard.Against.NullOrWhiteSpace(name, nameof(name));
_quantity = Guard.Against.NegativeOrZero(quantity, nameof(quantity));
_max = Guard.Against.Zero(max, nameof(max));
_unitPrice = Guard.Against.Negative(unitPrice, nameof(unitPrice));
_dateCreated = Guard.Against.OutOfSQLDateRange(dateCreated, nameof(dateCreated));
}
}
通过IGuardClause
实现扩展
namespace Ardalis.GuardClauses
{
public static class Extensions
{
public static string Foo(this IGuardClause guardClause, string input, string parameterName)
{
if(input?.ToLower() == "foo")
{
throw new ArgumentException("Should not have been foo", parameterName);
}
return input;
}
}
}
于是
_name = Guard.Against.Foo(name, nameof(name));