I am trying to create .net standard delegate, Action with the input parameter int
. But I am getting
Cannot implicitly convert type 'void' to System.Action.
I learned that same return type methods can be added to multicast delegates. Below is my code. What is the wrong with this code? I don't see a compilation error if I write lambda expression.
static void Main(string[] 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);
}
The code below compiles... The integer is expected to be passed when the Action is invoked.
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.
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);
}
Why not to use Lambda expressions ? In fact, you have already used it in this line of code:
AddBook += x => Console.WriteLine("Added book with :{0}" , x ); // No compile error here
This will result in:
Action<int> AddBook = (x) => AddBookwithId(x); // Here is the error
AddBook += (x) => Console.WriteLine("Added book with :{0}" , x ); // No compile error here
AddBook += (x) => AddBookwithISBN(x);// of course, the same error here too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.