2017-02-23 107 views
1

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

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

要调用在第一线的功能。等号的RHS是“AddBookwithId(15)”是一个函数调用。第二行是添加一个lambda表达式。加法赋值的RHS是'x => Console.WriteLine(...)'这是一个带参数'x'的lambda表达式和一个调用'Console.WriteLine()'的主体。第三行再次调用该函数。 RHS是'AddBookwithISBN(56434)',这是一个函数调用。 –

+0

AddBookwithId的值是对方法的引用。带有parens的AddBookwithId(15)'是该方法的一个*调用,所以AddBookwithId(15)'的值就是方法返回的值 - 在这种情况下为'void',什么也不是。您不希望将调用的结果提供给事件处理程序;你想告诉处理程序如何调用方法本身。因此你想给它一个方法的引用:'AddBookwithId'。 –

回答

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. 
+0

谢谢@shaneRay。我正在详细地学习代表,所以我越来越困惑,因为我进一步了解它。感谢澄清。 – Alienalone

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

谢谢这是完美的。 – Alienalone

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.  
相关问题