c# - 匿名函数没有返回正确的字符串

标签 c# delegates lambda stringbuilder

我有以下代码:

delegate string CD();
void MyFunction()
{
    stringBuilder.Append((CD)delegate()
    {
        switch(whatever)
        {
            case 1 : return "A";
            ...
            default: return "X";
        }
    });
}

但是 stringBuilder 附加文本 MyNamespace.MyClass+CD 而不是 AX。为什么会这样?

最佳答案

因为 StringBuilder.Append 在您提供的参数上调用了 ToString。就这是一个转换为 CD 的委托(delegate)而言,它返回它的类型。

要返回值 A 或 X,必须调用委托(delegate)。但是 Append 不需要委托(delegate),因此它不会调用它。

关于c# - 匿名函数没有返回正确的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7886584/

相关文章:

c# - 更好地理解委托(delegate),一些解释

jquery - 如何延迟 google 分析的 jquery 事件

python - AWS Lambda "Unable to import module ' 处理程序' : No module named handler"

c# - 五个线程处理任务列表 c#

c# - 尝试创建安装程序以使 XNA 游戏可在其他计算机上玩

ios - swift 委托(delegate)不工作

go - 当匿名函数在 golang 中永远等待 channel 时会发生什么?

ruby - 为什么 STDOUT 在 Ruby 中只显示一次返回的消息?

c# - 如何使用 ReflectionPermission 拒绝反射

c# - 嵌套开关?或其他检查不同条件的解决方案?