[英]Cannot implicitly convert type 'void' to System.Action<int>
I am trying to create .net standard delegate, Action with the input parameter int
. 我正在尝试使用输入参数
int
创建.net标准委托,Action。 But I am getting 但我得到了
Cannot implicitly convert type 'void' to System.Action.
无法将类型'void'隐式转换为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.
如果我写lambda表达式,我没有看到编译错误。
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时,应该传递整数。
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 ? 为什么不使用Lambda表达式 ? 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.