鼎鼎知识库
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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

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