|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- 往往在架构中`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));
- ```
-
|