【问题标题】:c# console.writeline error when adding the operator + " new"c#添加操作符+“new”时出现console.writeline错误
【发布时间】:2016-06-19 22:38:36
【问题描述】:

我正在使用下面的代码,我想在输出中添加一个字符串,但是我得到了这个错误

运算符“+”不能应用于“方法组”类型的操作数,并且 '字符串'。

     class Program
{
   static void Main(string[] args)
        {
            string sample = "1a2b3c4d";
            MatchCollection matches = Regex.Matches(sample, @"\d");

            List<myclass> matchesList = new List<myclass>();

            foreach (Match match in matches)
            {
                myclass class1 = new myclass();

                class1.variableX.Add(match.Value);

                matchesList.Add(class1);
            }

        foreach (myclass class2 in matchesList)
            class2.variableX.ForEach(Console.WriteLine + " "); // <---- ERROR


        }


}

这里是类

public class myclass
    {
         public List<string> variableX = new List<string>();
    }

【问题讨论】:

    标签: c# string string-matching console.writeline method-group


    【解决方案1】:

    如果您想在使用WriteLine 方法之前修改字符串,您有两种可能:

    • class2.variableX.ForEach(s =&gt; Console.WriteLine(s + " "));

    • class2.variableX.Select(s =&gt; s + " ").ForEach(Console.WriteLine);

    【讨论】:

    • 效果很好。但在我的大代码中,只有当我这样写时它才起作用:: ("" + s)。 ( s + " ") 另一个只显示 " " 里面的内容
    • 这可能是什么原因。
    • 我也不明白 .Select 做什么。非常感谢
    • Select 将序列的每个元素投影到一个新形式 MSDN。或一些 examples 的 Linq 函数。
    • 所以为什么它只适用于 invers > ( " " + s ) 而不是 ( s + " ")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多