Skip to content

Instantly share code, notes, and snippets.

@pinzolo
Created June 18, 2012 01:27
Show Gist options
  • Save pinzolo/2946301 to your computer and use it in GitHub Desktop.
Save pinzolo/2946301 to your computer and use it in GitHub Desktop.
Object クラス拡張
using System;
namespace MktSys.Lib.Extensions
{
/// <summary>
/// Object 拡張メソッド定義クラス
/// </summary>
public static class ObjectExtension
{
/// <summary>
/// オブジェクトに Tap メソッドを追加する。<br />
/// オブジェクト自身に指定の処理を行い、オブジェクト自身を返却する。
/// </summary>
/// <typeparam name="T">対象の型</typeparam>
/// <param name="source">対象オブジェクト</param>
/// <param name="action">処理</param>
/// <returns>対象オブジェクト自身</returns>
public static T Tap<T>(this T source, Action<T> action)
{
if (source == null || action == null) { return source; }
action(source);
return source;
}
}
}
// test
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting; // or NUnit.Framework
using MktSys.Lib.Extensions;
namespace MktSys.Lib.Extensions.Test
{
[TestClass]
public class ObjectExtensionTest
{
#region Object#Tap
[TestMethod]
public void TestTapReference()
{
var list = new List<int>() { 1, 2, 3, 4 };
var newList = list.Tap(l => l.Add(5));
Assert.ReferenceEquals(newList, list);
}
[TestMethod]
public void TestTapAction()
{
var list = new List<int>() { 1, 2, 3, 4 };
var expected = Enumerable.Range(1, 5);
var newList = list.Tap(l => l.Add(5));
Assert.AreEqual(5, list.Count);
Assert.IsTrue(list.SequenceEqual(expected));
Assert.AreEqual(5, newList.Count);
Assert.IsTrue(newList.SequenceEqual(expected));
}
[TestMethod]
public void TestTapWithNullSource()
{
var actionExecuted = false;
Object obj = null;
obj.Tap(_ => actionExecuted = true);
Assert.IsFalse(actionExecuted);
}
[TestMethod]
public void TestTapWithNullAction()
{
var actionExecuted = false;
Object obj = new Object();
obj.Tap(null);
Assert.IsFalse(actionExecuted);
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment