鼎鼎知识库
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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));