C# と VB.NET の質問掲示板

ASP.NET、C++/CLI、Java 何でもどうぞ

ログ内検索
  • キーワードを複数指定する場合は 半角スペース で区切ってください。
  • 検索条件は、(AND)=[A かつ B] (OR)=[A または B] となっています。
  • [返信]をクリックすると返信ページへ移動します。
キーワード/ 検索条件 /
検索範囲/ 強調表示/ ON (自動リンクOFF)
結果表示件数/ 記事No検索/ ON
大文字と小文字を区別する

No.90414 の関連記事表示

<< 0 >>
■90414  Re[1]: 引数のあるメソッドをメソッドに渡す
□投稿者/ 魔界の仮面弁士 -(2019/03/09(Sat) 13:11:11)
    2019/03/09(Sat) 13:26:31 編集(投稿者)

    No90412 (B.B さん) に返信
    > delegate int SimpleFunc(int x);
    > private int hogeMethod(SimpleFunc func)

    .NET Framework 3.5 以降をお使いであれば、Func<> や Action<> が用意されているので、
      private int hogeMethod(Func<int, int> func)
    で済ますこともできますね。


    > しかしデリゲードはなかったことにしろという文言をよく見かけます
    デリゲート(delegate)ですよ;
    デリゲードでもデリケートでも無く。


    > #90396で教えていただいた
    > isSuccessful = hogeMethod(() => Method3("ほげほげ"));
    > のようなラムダ式での記述の仕方を教えて欲しいのです

    どの部分を書き換えたいのかが読み取れなかったのですが、
    > private int method1(int i)
    > {
    >   i = i * 2;
    >   return i;
    > }
    については、「式形式」のメソッドで書けます。


    // 要 C# 6.0 以降
    private int method1(int i) => i * 2;


    hogeMethod(SimpleFunc func) の書き換えなら、
     private int hogeMethod(SimpleFunc func) => func(10);
     private int hogeMethod(SimpleFunc func) => (func ?? delegate { return -1; })(10);
     private int hogeMethod(SimpleFunc func) => func?.Invoke(10) ?? -1;
     private int hogeMethod(SimpleFunc func)=> func != null ? func(10) : throw new ArgumentNullException(nameof(func), "引数が空やで");
    とか。


    button1 での「int result = hogeMethod(method1);」のところで
    method1 メソッドを定義せずに呼び出したいなら、

    // 要 C# 2.0 以降
    SimpleFunc proc = new SimpleFunc(delegate(int i) { i *= 2; return i; });
    int result = hogeMethod(proc);

    // 要 C# 2.0 以降
    SimpleFunc proc = delegate(int i) { i *= 2; return i; };
    int result = hogeMethod(proc);

    // 要 C# 3.0 以降
    SimpleFunc proc = (int i) => { i *= 2; return i; };
    int result = hogeMethod(proc);

    // 要 C# 3.0 以降
    SimpleFunc proc = (i) => { i *= 2; return i; };
    int result = hogeMethod(proc);

    // 要 C# 3.0 以降
    SimpleFunc proc = i => { i *= 2; return i; };
    int result = hogeMethod(proc);



    // 要 C# 2.0 以降
    SimpleFunc proc = delegate(int i) { return i * 2; };
    int result = hogeMethod(proc);

    // 要 C# 2.0 以降
    int result = hogeMethod(delegate (int i) { return i * 2; });

    // 要 C# 3.0 以降
    SimpleFunc proc = i => { return i * 2; };
    int result = hogeMethod(proc);

    // 要 C# 3.0 以降
    int result = hogeMethod(i => { return i * 2; });

    // 要 C# 3.0 以降
    int result = hogeMethod(i => i * 2);
記事No.90412 のレス /過去ログ156より / 関連記事表示
削除チェック/



<< 0 >>

パスワード/

- Child Tree -