4

メソッドからアクションを返す方法を見つけようとしています。このオンラインの例は見つかりません。実行しようとしているコードは次のとおりですが、失敗します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            var testAction = test("it works");
            testAction.Invoke();    //error here
            Console.ReadLine();
        }

        static Action<string> test(string txt)
        {
            return (x) => Console.WriteLine(txt);
        }
    }
}
4

4 に答える 4

4

問題はtextActionですAction<string>。つまり、文字列を渡す必要があります。

textAction("foo");

次のようなものが必要だと思います:

class Program
{
    static void Main(string[] args)
    {
        var testAction = test();
        testAction("it works");
        // or textAction.Invoke("it works");
        Console.ReadLine();
    }

    // Don't pass a string here - the Action<string> handles that for you..
    static Action<string> test()
    {
        return (x) => Console.WriteLine(x);
    }
}
于 2013-02-07T18:33:03.667 に答える
3

返されるアクションは、パラメーターとして a を受け入れstringます。あなたInvokeがそのパラメータを提供する必要があるとき:

testAction("hello world");

もちろん、アクションはそのパラメーターを無視するため、より適切な修正は、パラメーターを受け入れないようにアクションを変更することです。

static Action test(string txt)
{
    return () => Console.WriteLine(txt);
}

これで、プログラムは期待どおりに動作します。

于 2013-02-07T18:33:58.283 に答える
2

あなたが持っているのはAction<String>呼び出しであるため、アクションを実行している文字列を含める必要があります。

testAction.Invoke("A string");

動作するはずです

于 2013-02-07T18:33:12.453 に答える
1

作成するアクションは、パラメーターなしで呼び出すことができるように、パラメーターなしにする必要があります。したがって、 の戻り値の型を変更し、宣言したが使用しなかったものtestも削除しxます。

    static Action test(string txt)
    {
        return () => Console.WriteLine(txt);
    }

次に、呼び出しコードが機能します。

        var testAction = test("it works"); // store the string in txt
        testAction.Invoke();
        Console.ReadLine();
于 2013-02-07T18:33:22.070 に答える