1+ using System . ComponentModel ;
12using System . Diagnostics . CodeAnalysis ;
23
34namespace ValueOf . Extensions . Examples ;
45
5- public interface IValueOfParsable < TU , T > : IParsable < T > where T : ValueOf < TU , T > , IParsable < T > , new ( )
6+ public interface IParsableValueOf < TU , T > : IParsable < T > where T : ValueOf < TU , T > , IParsable < T > , new ( )
67{
7- public static T Parse ( string s , IFormatProvider ? provider )
8+ static T IParsable < T > . Parse ( string s , IFormatProvider ? provider )
89 {
9- throw new NotImplementedException ( ) ;
10+ var converter = TypeDescriptor . GetConverter ( typeof ( T ) ) ;
11+ return ( T ) converter . ConvertFrom ( s ) ! ;
1012 }
1113
12- public static bool TryParse ( [ NotNullWhen ( true ) ] string ? s , IFormatProvider ? provider , [ MaybeNullWhen ( false ) ] out T result )
14+ static bool IParsable < T > . TryParse ( [ NotNullWhen ( true ) ] string ? s , IFormatProvider ? provider ,
15+ [ MaybeNullWhen ( false ) ] out T result )
1316 {
14- throw new NotImplementedException ( ) ;
17+ result = default ( T ) ;
18+ var converter = TypeDescriptor . GetConverter ( typeof ( T ) ) ;
19+ if ( converter . CanConvertFrom ( typeof ( string ) ) )
20+ {
21+ result = ( T ) converter . ConvertFrom ( s ) ! ;
22+ return true ;
23+ }
24+
25+ return false ;
1526 }
1627}
1728
18- public sealed class UserId : ValueOf < int , UserId > , IValueOfParsable < int , UserId >
29+ public sealed class UserId : ValueOf < int , UserId > , IParsableValueOf < int , UserId >
1930{
2031 protected override void Validate ( )
2132 {
2233 var userId = Value ;
2334 if ( userId <= 0 )
2435 throw new ArgumentOutOfRangeException ( nameof ( userId ) + $ " must be positive integer but is: { userId } ") ;
2536 }
26-
2737}
0 commit comments