无法将类型'void'隐式转换为System.Action <int>

时间:2017-02-23 18:24:29

标签: c# delegates action

我正在尝试使用输入参数int创建.net标准委托,Action。但我得到“不能隐式地将类型'void'转换为System.Action”。我了解到可以将相同的返回类型方法添加到多播委托。以下是我的代码。这段代码有什么问题?如果我写lambda表达式,我看不到编译错误。

    static void Main(strng[] args)
    {

    Action<int> AddBook = AddBookwithId(15); // Here is the error
    AddBook += x => Console.WriteLine("Added book with :{0}" , x ); // No compile error here
    AddBook += AddBookwithISBN(56434);// of course, the same error here too.
    }
    public static void AddBookwithId(int y)
    {
        Console.WriteLine( "Added Book to the shelf with the ID : {0} ", y ); 
    }

    public static void AddBookwithISBN(int y)
    {
        Console.WriteLine("Added Book to the shelf  with the ISBN: {0} ", y + 2);
    }

3 个答案:

答案 0 :(得分:2)

下面的代码编译...调用Action时,预期会传递整数。

       Action<int> AddBook = AddBookwithId; // Here is the error
       AddBook += x => Console.WriteLine("Added book with :{0}", x); // No compile error here
       AddBook += AddBookwithISBN;// of course, the same error here too.

答案 1 :(得分:1)

    delegate void AddBook(int y);

    static void Main()
    {

        AddBook addBook;
        bool IsISBN = false;

        if (IsISBN)
        {
            addBook = AddBookwithISBN;
        }
        else
        {
            addBook = AddBookwithId;
        }
        addBook += x => Console.WriteLine("Added book with :{0}", x);
    }
    public static void AddBookwithId(int y)
    {
        Console.WriteLine("Added Book to the shelf with the ID : {0} ", y);

    }

    public static void AddBookwithISBN(int y)
    {
        Console.WriteLine("Added Book to the shelf  with the ISBN: {0} ", y + 2);
    }

答案 2 :(得分:0)

为什么不使用Lambda expressions? 实际上,您已经在这行代码中使用过它:

Data

这将导致:

AddBook += x => Console.WriteLine("Added book with :{0}" , x ); // No compile error here