Lambda expression C# failed to convert to the obje

2019-09-03 10:12发布

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?

3条回答
不美不萌又怎样
2楼-- · 2019-09-03 10:51

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

查看更多
We Are One
3楼-- · 2019-09-03 10:56

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);}
        );
    }
}
查看更多
ら.Afraid
4楼-- · 2019-09-03 11:08

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.

查看更多
登录 后发表回答