Browse Source

Make `T To<T>` extension method support string to GUID.

https://github.com/aspnetboilerplate/aspnetboilerplate/pull/2330/
pull/5445/head
maliming 6 years ago
parent
commit
483818ea42
  1. 14
      framework/src/Volo.Abp.Core/System/AbpObjectExtensions.cs
  2. 6
      framework/test/Volo.Abp.Core.Tests/System/ObjectExtension_Test.cs

14
framework/src/Volo.Abp.Core/System/AbpObjectExtensions.cs

@ -1,4 +1,5 @@
using System.Globalization;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
namespace System
@ -9,7 +10,7 @@ namespace System
public static class AbpObjectExtensions
{
/// <summary>
/// Used to simplify and beautify casting an object to a type.
/// Used to simplify and beautify casting an object to a type.
/// </summary>
/// <typeparam name="T">Type to be casted</typeparam>
/// <param name="obj">Object to cast</param>
@ -29,6 +30,11 @@ namespace System
public static T To<T>(this object obj)
where T : struct
{
if (typeof(T) == typeof(Guid))
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(obj.ToString());
}
return (T)Convert.ChangeType(obj, typeof(T), CultureInfo.InvariantCulture);
}
@ -42,7 +48,7 @@ namespace System
{
return list.Contains(item);
}
/// <summary>
/// Can be used to conditionally perform a function
/// on an object and return the modified or the original object.
@ -65,7 +71,7 @@ namespace System
return obj;
}
/// <summary>
/// Can be used to conditionally perform an action
/// on an object and return the original object.

6
framework/test/Volo.Abp.Core.Tests/System/ObjectExtension_Test.cs

@ -35,6 +35,8 @@ namespace System
Assert.Throws<FormatException>(() => "test".To<bool>());
Assert.Throws<FormatException>(() => "test".To<int>());
"2260AFEC-BBFD-42D4-A91A-DCB11E09B17F".To<Guid>().ShouldBeOfType<Guid>().ShouldBe(new Guid("2260afec-bbfd-42d4-a91a-dcb11e09b17f"));
}
[Fact]
@ -57,10 +59,10 @@ namespace System
public void If_Tests()
{
var value = 0;
value = value.If(true, v => v + 1);
value.ShouldBe(1);
value = value.If(false, v => v + 1);
value.ShouldBe(1);

Loading…
Cancel
Save