Lambda表达式C#无法转换为对象类型,并以ref引起失败 [英] Lambda expression C# failed to convert to the object type and fail with ref

查看:526
本文介绍了Lambda表达式C#无法转换为对象类型,并以ref引起失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样的功能:

   private static void EncodeString(ref string str)
    {
        using (RLE inst_rle = new RLE())
        {
            string str_encoded = inst_rle.Encode(ref str);
            Console.WriteLine(

              "\r\nBase string ({0} chars): {1}\r\nAfter RLE-encoding ({2} chars): {3}\r\nCompression percentage: %{4}",
              str.Length, str, str_encoded.Length, str_encoded,
              () => { (100 * (str.Length - str.encoded.Length) / str.Length); }

                             );
        }
    }

我记得这是C#中的lambdas风格: ()=> {<动作>;

As I remember it's a style of lambdas in C#: () => { < action > ; }

但是得到这样的错误:


  • 无法转换lambda表达式键入对象,因为

  • 只有赋值,调用,增量,减量和新的对象表达式才能用作语句 li>
  • 不能在匿名方法,lambda表达式或查询表达式中使用ref或out参数'str'

  • 不能在匿名方法,lambda表达式或查询表达式中使用ref或out参数'str'

  • Cannot convert lambda expression to type 'object' because it
  • Only assignment, call, increment, decrement, and new object expressions can be used as a statement
  • Cannot use ref or out parameter 'str' inside an anonymous method, lambda expression, or query expression
  • Cannot use ref or out parameter 'str' inside an anonymous method, lambda expression, or query expression

代理服务器中的C#EXACLTY中的Lambda如何在我的应用程序(控制台应用程序)中使用Lambda / Func< T>,如()=> {}

推荐答案

我不太确定为什么你想在这里使用一个lambda,它看起来像你想要的:

I'm not really sure why you want to use a lambda here, it looks like you want:

Console.WriteLine(@"\r\nBase string ({0} chars): {1}\r\nAfter RLE-encoding
            (
             {2} chars): {3}\r\nCompression percentage: {4}",
             str.Length, str, str_encoded.Length, str_encoded,
             (100 / str.Length) * (str.Length / str_encoded.Length)
            );

正如评论指出的那样,您需要在格式字符串前加一个 @ ,因为它跨越多行。

As the comment points out, you need to prefix the format string with an @ since it spans multiple lines.

这篇关于Lambda表达式C#无法转换为对象类型,并以ref引起失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆