Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ジェネリックと拡張メソッドを使ってみる

Last updated at Posted at 2012-12-26

以前こちらの記事で作成したBetween()メソッドですが、

ジェネリックと拡張メソッドを使えば、より汎用的で使いやすくなります。

書きなおしたメソッド

Between.cs
public static class MyGeneral	// 静的クラス
{
    // 静的クラスなのでコンストラクタは無し
    
    /// <summary>
    /// 数値 current がlower ~ higher の範囲内か?(Generic版)		
    /// </summary>
    /// <param name="lower">区間(開始)</param>
    /// <param name="current">比較される値</param>
    /// <param name="higher">区間(終了)</param>
    /// <param name="inclusive">閉区間か?(境界値を含む) (初期値:true)</param>
    /// <returns>範囲内であればtrue</returns>
    public static bool isBetween<T>(this T current, T lower,  T higher, bool inclusive = true) where T : IComparable
    {
        // 拡張メソッドは1つ目の引数に this キーワードを付ける

        // ジェネリックだと比較演算子が使えなくなってしまうので、
        // where句 で型パラメーター T が IComparable<T> インターフェイスを実装するように指定
        // CompareTo() メソッドが使えるようになる。
        if(lower.CompareTo(higher) > 0 ) Swap(ref lower,ref higher);
    
        return inclusive ?
            (lower.CompareTo(current) <= 0 && current.CompareTo(higher) <= 0 ) :
            (lower.CompareTo(current) <  0 && current.CompareTo(higher) <  0 );
    }
    
    /// <summary>
    /// 2つの値a,bを交換する
    /// </summary>
    /// <param name="a">値A</param>
    /// <param name="b">値B</param>
    public static void Swap<T>(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }
}

このように書くことで、
Rubyみたいに、以下の様なわかりやすい構文で記述することができます。
あたかも、int や string のインスタンスメソッドみたいに。

bool inRange;
inRange = 2.isBetween(1,3);  // true
inRange = "b".isBetween("a","c");  // true

参考

10
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?