25

名前を付けないでラムダ式のいくつかの引数を破棄することは可能ですか? たとえば、Action<int,int> を渡す必要がありますが、2 番目のパラメーターにのみ関心があるため、次のようなものを書きたいと考えています。

(_, foo) => bar(foo)
// or
(, foo) => bar(foo)

最初のケースでは、それは機能しています。ただし、最初のパラメーターは名前が「_」であるため、実際には名前が付けられていません。そのため、2つ以上破棄したい場合は機能しません。プロローグでは「任意の値」という意味があるため、_ を選択します。

そう。私のユースケースに特別な文字や表現はありますか?

4

4 に答える 4

19

No, you can't. Looking at the C# language specification grammar, there are two ways to declare lambdas: explicit and implicit. Neither one allows you to skip the identifier of the parameter or to reuse identifiers (names).

explicit-anonymous-function-parameter:
  anonymous-function-parameter-modifieropt   type   identifier

implicit-anonymous-function-parameter:
  identifier

It's the same as for unused function parameters in ordinary functions. They have to be given a name.

Of course you can use _ as the name for one of the parameters, as it is a valid C# name, but it doesn't mean anything special.

As of C# 7, _ does have a special meaning. Not for lambda expression parameter names but definitely for other things, such as pattern matching, deconstruction, out variables and even regular assignments. (For example, you can use _ = 5; without declaring _.)

于 2012-12-10T07:57:53.040 に答える
8

簡単に言えば、いいえ、すべてのパラメーターに名前を付ける必要があり、名前は一意である必要があります。

_C# では有効な識別子であるため、1 つのパラメーター名として 使用できます。
ただし、一度しか使えません。

于 2012-12-10T07:57:10.780 に答える