Browse Source

Added If object extension.

pull/4161/head
Halil İbrahim Kalkan 6 years ago
parent
commit
16968cfc7c
  1. 45
      framework/src/Volo.Abp.Core/System/AbpObjectExtensions.cs
  2. 17
      framework/test/Volo.Abp.Core.Tests/System/ObjectExtension_Test.cs

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

@ -42,5 +42,50 @@ 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.
/// It is useful for chained calls.
/// </summary>
/// <param name="obj">An object</param>
/// <param name="condition">A condition</param>
/// <param name="func">A function that is executed only if the condition is <code>true</code></param>
/// <typeparam name="T">Type of the object</typeparam>
/// <returns>
/// Returns the modified object (by the <paramref name="func"/> if the <paramref name="condition"/> is <code>true</code>)
/// or the original object if the <paramref name="condition"/> is <code>false</code>
/// </returns>
public static T If<T>(this T obj, bool condition, Func<T, T> func)
{
if (condition)
{
return func(obj);
}
return obj;
}
/// <summary>
/// Can be used to conditionally perform an action
/// on an object and return the original object.
/// It is useful for chained calls on the object.
/// </summary>
/// <param name="obj">An object</param>
/// <param name="condition">A condition</param>
/// <param name="action">An action that is executed only if the condition is <code>true</code></param>
/// <typeparam name="T">Type of the object</typeparam>
/// <returns>
/// Returns the original object.
/// </returns>
public static T If<T>(this T obj, bool condition, Action<T> action)
{
if (condition)
{
action(obj);
}
return obj;
}
}
}

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

@ -52,5 +52,22 @@ namespace System
str = null;
str.IsIn("a", "b", "c").ShouldBe(false);
}
[Fact]
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);
value = value
.If(true, v => v + 3)
.If(false, v => v + 5);
value.ShouldBe(4);
}
}
}

Loading…
Cancel
Save