简体   繁体   中英

How can I debug this error: “Cannot Convert Lambda Expression to String”?

I am trying to debug the following code, but it is not working.

I upload this pic http://i68.tinypic.com/2rqoaqc.jpg

This is my code:

using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {   
         string input = "code1,code2,#c55+35+97#g,coden,code3,code4,#c44+25+07#gcoden";

         string output = Regex.Replace(
             input, 
             "#c(.*?)#g", 
             m => "#c" + m.Groups[1].Value.Split('+').Sum(int.Parse) + "#");

         Console.WriteLine(output);    
    }
}

And these are the errors I am getting:

ERROR 1:

'int int.Parse(string)' has the wrong return type (CS0407) -

ERROR 2:

The call is ambiguous between the following methods or properties: 'System.Linq.Enumerable.Sum(System.Collections.Generic.IEnumerable, System.Func)' and 'System.Linq.Enumerable.Sum(System.Collections.Generic.IEnumerable, System.Func)' (CS0121)

ERROR 3: - Cannot convert m "lambda" to string

Cannot convert lambda expression to type 'string' because it is not a delegate type (CS1660)

You need to use an explicit lambda rather than int.Parse() :

    string output = Regex.Replace(
        input,
        "#c(.*?)#g",
        m => "#c" + m.Groups[1].Value.Split('+').Sum(v => int.Parse(v)) + "#");

Notice I replaced int.Parse with v => int.Parse(v) . Sample fiddle .

Interestingly enough, this compiles and works as desired in c# 6.0:

    string output = Regex.Replace(
        input,
        "#c(.*?)#g",
        m => "#c" + m.Groups[1].Value.Split('+').Sum(int.Parse) + "#");

Sample Roslyn fiddle . I'm not sure where this change is documented, maybe under New Language Features in C# 6: Improved overload resolution :

There are a number of small improvements to overload resolution, which will likely result in more things just working the way you'd expect them to. The improvements all relate to “betterness” – the way the compiler decides which of two overloads is better for a given argument.

One place where you might notice this (or rather stop noticing a problem!) is when choosing between overloads taking nullable value types. Another is when passing method groups (as opposed to lambdas) to overloads expecting delegates. The details aren't worth expanding on here – just wanted to let you know!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM