鼎鼎知识库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2、比throw更好的处理方式.md 1.5KB

3 jaren geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 往往在架构中`throw`随处可见。
  2. ```
  3. throw new ArgumentException($"Input {parameterName} was not in required format", parameterName);
  4. ```
  5. `Ardalis.GuardClauses`用来解决这个问题。
  6. ```
  7. <ItemGroup>
  8. <PackageReference Include="Ardalis.GuardClauses" Version="3.0.1" />
  9. </ItemGroup>
  10. ```
  11. 用法
  12. ```
  13. public class Order
  14. {
  15. private string _name;
  16. private int _quantity;
  17. private long _max;
  18. private decimal _unitPrice;
  19. private DateTime _dateCreated;
  20. public Order(string name, int quantity, long max, decimal unitPrice, DateTime dateCreated)
  21. {
  22. _name = Guard.Against.NullOrWhiteSpace(name, nameof(name));
  23. _quantity = Guard.Against.NegativeOrZero(quantity, nameof(quantity));
  24. _max = Guard.Against.Zero(max, nameof(max));
  25. _unitPrice = Guard.Against.Negative(unitPrice, nameof(unitPrice));
  26. _dateCreated = Guard.Against.OutOfSQLDateRange(dateCreated, nameof(dateCreated));
  27. }
  28. }
  29. ```
  30. 通过`IGuardClause`实现扩展
  31. ```
  32. namespace Ardalis.GuardClauses
  33. {
  34. public static class Extensions
  35. {
  36. public static string Foo(this IGuardClause guardClause, string input, string parameterName)
  37. {
  38. if(input?.ToLower() == "foo")
  39. {
  40. throw new ArgumentException("Should not have been foo", parameterName);
  41. }
  42. return input;
  43. }
  44. }
  45. }
  46. ```
  47. 于是
  48. ```
  49. _name = Guard.Against.Foo(name, nameof(name));
  50. ```