【问题标题】:Cannot implicitly convert type 'void' to System.Action<int>无法将类型“void”隐式转换为 System.Action<int>
【发布时间】:2017-02-23 18:24:29
【问题描述】:

我正在尝试使用输入参数 int 创建 .net 标准委托 Action。但我得到了

无法将类型“void”隐式转换为 System.Action。

我了解到可以将相同的返回类型方法添加到多播委托中。下面是我的代码。这段代码有什么问题?如果我编写 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);
}

【问题讨论】:

  • 你在第一行调用函数。等号的RHS是AddBookwithId(15)是一个函数调用。第二行是添加一个 lambda 表达式。 add-assignment 的 RHS 是 x =&gt; Console.WriteLine(...),它是一个带有参数 x 和一个调用 Console.WriteLine() 的主体的 lambda 表达式。第三行再次调用该函数。 RHS 是AddBookwithISBN(56434),这是一个函数调用。
  • AddBookwithId 的值是对方法的引用。带括号的AddBookwithId(15) 是对方法的调用,所以AddBookwithId(15) 的值就是方法返回的值——在这种情况下void 什么都没有。您不想将调用结果提供给事件处理程序;您想告诉处理程序如何调用方法本身。因此你想给它一个方法的引用:AddBookwithId.

标签: c# delegates action


【解决方案1】:

下面的代码编译...当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.

【讨论】:

  • 谢谢@shaneRay。我正在详细学习代表,所以当我深入了解它时,我会感到困惑。感谢您的澄清。
【解决方案2】:
    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);
    }

【讨论】:

  • 谢谢 这是完美的。
【解决方案3】:

为什么不使用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.    

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    相关资源
    最近更新 更多