使用不同构造函数参数的Func和Action之间是否不一致?

时间:2016-06-19 18:41:57

标签: c# action anonymous-function func

我正在研究一个twitch聊天机器人,在我的Command.cs课程中,我遇到了一个奇怪的问题。我有一个带Action<string, User, Channel>的构造函数和一个带Func<string, User, Channel, bool>的构造函数。第一个构造函数应该用Func调用第二个构造函数,调用Action并返回true。当我在两个构造函数中使用7个参数时,这工作正常,但是当我添加第8个参数时,它就停止了编译。

我得到的错误是CS8030&#34;转换为void的匿名函数返回委托不能返回值。&#34;但在我添加第8个参数之前,代码编译得很好

两个片段之间的唯一区别是我添加了额外的description参数。

之前:

public class Command
{
    public Command(string name, Action<string, User, Channel> action, bool adminOnly = false, bool modOnly = false, bool ownerOnly = false, bool hasUserCooldown = true, TimeSpan? cooldown = null, bool allowOtherCommands = false)
        : this(name, (m, u, c) => { action(m, u, c); return true; }, adminOnly, modOnly, ownerOnly, hasUserCooldown, cooldown)
    {

    }

    public Command(string name, Func<string, User, Channel, bool> action, bool adminOnly = false, bool modOnly = false, bool ownerOnly = false, bool hasUserCooldown = true, TimeSpan? cooldown = null, bool allowOtherCommands = false)
    {

    }
}

public class User { }
public class Channel { }

后:

public class Command
{
    public Command(string name, Action<string, User, Channel> action, bool adminOnly = false, bool modOnly = false, bool ownerOnly = false, bool hasUserCooldown = true, TimeSpan? cooldown = null, bool allowOtherCommands = false, string description = null)
        : this(name, (m, u, c) => { action(m, u, c); return true; }, adminOnly, modOnly, ownerOnly, hasUserCooldown, cooldown, description)
    {

    }

    public Command(string name, Func<string, User, Channel, bool> action, bool adminOnly = false, bool modOnly = false, bool ownerOnly = false, bool hasUserCooldown = true, TimeSpan? cooldown = null, bool allowOtherCommands = false, string description = null)
    {

    }
}

public class User { }
public class Channel { }

非常感谢。

1 个答案:

答案 0 :(得分:1)

在两个版本中,您忘记将allowOtherCommands可选参数传递给第二个方法。虽然在第一种方法中,它只是编译器无法捕获的逻辑错误,但在第二种情况下,description参数导致编译器将调用映射到期望{{ 1}},因此错误。

只需传递所有可选参数即可解决问题:

Action