Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Last active February 9, 2018 05:49
Show Gist options
  • Save ufcpp/c6bca9e382c579b25f618bf9befbefae to your computer and use it in GitHub Desktop.
Save ufcpp/c6bca9e382c579b25f618bf9befbefae to your computer and use it in GitHub Desktop.
カリー化するとチョットハヤイ
using System;
static class Program
{
static void M(Action<int> a)
{
a(10);
}
static void Main()
{
Action<long> a = x => Console.WriteLine(x);
#if InvalidCode
//❌コンパイル エラー。int → long へは共変性が働かないので、直接は渡せない
M(a);
#endif
// ラムダ式で包めば渡せる
M(x => a(x));
// 拡張メソッドでカリー化(ちょっとだけ速い)
M(a.Upcast);
}
static void Upcast(this Action<long> a, int x) => a(x);
}
using System;
static class Program
{
static void M(Func<long> f)
{
Console.WriteLine(f());
}
static void Main()
{
Func<int> f = () => 1;
#if InvalidCode
//❌コンパイル エラー。int → long へは共変性が働かないので、直接は渡せない
M(f);
#endif
// ラムダ式で包めば渡せる
M(() => f());
// 拡張メソッドでカリー化(ちょっとだけ速い)
M(f.Upcast);
}
static long Upcast(this Func<int> f) => f();
}
using System;
static class Program
{
static void M(Func<int> f)
{
Console.WriteLine(f());
}
static void Main()
{
var s = Console.ReadLine();
// ラムダ式を利用(ちょっとだけ遅い)
M(() => s.Length);
// 拡張メソッドでカリー化(ちょっとだけ速い)
M(s.GetLength);
}
static int GetLength(this string s) => s.Length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment