ufcpp / UfcppSample

http://ufcpp.net/ 向けのサンプル
Apache License 2.0
133 stars 41 forks source link

Lambda default parameters #439

Closed ufcpp closed 11 months ago

ufcpp commented 1 year ago

csharplang 6051

https://ufcpp.net/blog/2023/1/lambda-default/ を清書。

https://ufcpp.net/study/csharp/sp3_lambda.html に追記。 https://ufcpp.net/study/csharp/cheatsheet/ap_ver10/#lambda-improvement とも関連。

ufcpp commented 1 year ago

リフレクションで情報取ったとき、Delegate.Method から取るか、 GetType からの Type.GetMethod で取るかで値が違う例:

using System.Reflection;

A a = (int x = 2) => { };

MethodInfo m1 = a.Method;
MethodInfo m2 = a.GetType().GetMethod("Invoke")!;

Console.WriteLine(m1.GetParameters()[0].DefaultValue); // 2
Console.WriteLine(m2.GetParameters()[0].DefaultValue); // 1

delegate void A(int x = 1);
ufcpp commented 1 year ago

型とラムダ式で違うデフォルト値指定できる。 型の方優先。 さすがに警告は出してくれる。

D d = (int x = 2) => x; // 警告出る。

Console.WriteLine(d()); // 1 の方になる。

delegate int D(int x = 1);
ufcpp commented 11 months ago

https://ufcpp.net/study/csharp/functional/fun_localfunctions/#lambda-default https://ufcpp.net/study/csharp/cheatsheet/ap_ver12/#lambda-default