カリー化するとチョットハヤイ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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