Lambda expression C# failed to convert to the object type and fail with ref

折月煮酒 提交于 2019-12-24 21:07:31

问题


Have such function:

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

                             );
        }
    }

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

But getting such errors:

  • 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

How to use Lambda in C# EXACLTY in my app (console app) without explicity using

Delegate / Func< T >, like in () => { } way?


回答1:


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.




回答2:


I agree with Lee, but when you really want to create a Lamba like this, and get its output you need to cast explicitly something like:

(Func<int>)(() => (100 / str.Length) * (str.Length / str_encoded.Length)))();

I do this when I am playing with threads, not in production code though




回答3:


String constants can be defined over multiple code lines with a @ prefix, but then your \r\n will not work. So instead you can add string framgents together with + to achieve the same effect:

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.Length / str_encoded.Length);}
        );
    }
}


来源:https://stackoverflow.com/questions/14185007/lambda-expression-c-sharp-failed-to-convert-to-the-object-type-and-fail-with-ref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!