首页 文章

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

提问于
浏览
1

我正在尝试使用输入参数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 回答

  • 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
    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);
        }
    
  • 0

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

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

    这将导致:

    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.
    

相关问题