Possibility of external functions as nullable guards?

前端 未结 2 1364
囚心锁ツ
囚心锁ツ 2020-12-06 13:39

C# 8 introduced nullable reference types, which is a very cool feature. Now if you expect to get nullable values you have to write so-called guards:



        
2条回答
  •  一整个雨季
    2020-12-06 14:16

    There is a Guard Clauses library by Steve Ardalis that I think can help you with this situation. You can do things like:

    • Guard.Against.Null (throws if input is null)
    • Guard.Against.NullOrEmpty (throws if string or array input is null or empty)
    • Guard.Against.NullOrWhiteSpace (throws if string input is null, empty or whitespace)
    • Guard.Against.OutOfRange (throws if integer/DateTime/enum input is outside a provided range)
    • Guard.Against.OutOfSQLDateRange (throws if DateTime input is outside the valid range of SQL Server DateTime values)
    • Guard.Against.Zero (throws if number input is zero)

    In this blog post Jason Roberts made a quick explanation of the library too.

    There is another Guard Class in the Microsoft.Toolkit.Diagnostics namespace but probably is not viable in all the use cases that will depend if wanna add that dependency to the project or not.

提交回复
热议问题