3
2

More than 5 years have passed since last update.

C#で貧者の型クラス(poor man's type class)

Posted at

今日はScala の implicit parameter は型クラスの一種とはどういうことなのかの例をC#で書いてみます。と言っても、C#には暗黙引数と同等の機能は備わっていないので、明示的に引数を取るしかありません。

型クラス。

public abstract class FlipFlapper<T>
{
    public abstract T DoFlipFlap(T x);
}

型クラスを利用する関数。

private static T FlipFlap<T>(T x, FlipFlapper<T> flipFlapper)
{
    return flipFlapper.DoFlipFlap(x);
}

型クラスの実体。

public class IntFlipFlapper : FlipFlapper<int>
{
    public static IntFlipFlapper Instance = new IntFlipFlapper();

    public override int DoFlipFlap(int x)
    {
        return -x;
    }
}

public class StringFlipFlapper : FlipFlapper<string>
{
    public static StringFlipFlapper Instance = new StringFlipFlapper();

    public override string DoFlipFlap(string x)
    {
        char[] chars = x.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
}

型クラスを利用する関数の呼び出し。

FlipFlap(1, IntFlipFlapper.Instance);
FlipFlap("string", StringFlipFlapper.Instance);

毎回明示的に引数を渡さなければならないのは不便です。何とかしてC#で暗黙引数を実現できないか色々考えましたが、難しそうでした。

3
2
0

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
3
2