[英]C# cannot convert 'string' to 'System.Collections.Generic.IEnumerable<string>
I'm new with C# how can I fix the issue?我是 C# 的新手,我该如何解决这个问题? The error is showing at the last line(query).错误显示在最后一行(查询)。 Any help is appreciated!任何帮助表示赞赏!
using System;
using System.Collections.Generic;
using System.IO;
namespace file
{
class Program
{
static void Main(string[] args)
{
var hobbies = new List<string>() { };
Console.WriteLine("Please enter your name");
string myName = Console.ReadLine();
Console.WriteLine("Tell me something about you");
string myAbout = Console.ReadLine();
Console.WriteLine("What kind of hobbies do you have?");
string myHobbies = Console.ReadLine();
hobbies.Add(myHobbies);
var query = myName + '\n' + myAbout + '\n' + myHobbies;
File.AppendAllLines("C:\\test.txt", query);
}
}
}
As states in the docs for File.AppendAllLines
, the method signature is正如File.AppendAllLines
的文档中所述,方法签名是
public static void AppendAllLines (string path,
System.Collections.Generic.IEnumerable<string> contents);
ie the second argument is expected to be an IEnumerable<String>
and you are passing query
, which is a String
.即第二个参数应该是一个IEnumerable<String>
并且你正在传递query
,它是一个String
。 You probably want AppendAllText
, which receives a String in the second argument.您可能想要AppendAllText
,它在第二个参数中接收一个字符串。
The method expects a collection of strings as second parameter, but you provide only a string.该方法需要一个字符串集合作为第二个参数,但您只提供一个字符串。 You can use File.AppendAllText instead which works with a single string.您可以使用 File.AppendAllText 代替它与单个字符串一起使用。
File.AppendAllText("C:\\test.txt", query);
You'll really get that error since your trying to combine a List into a string.自从您尝试将 List 组合成字符串后,您真的会遇到该错误。 Just iterate first whats inside of your List in a string that will hold its values before proceeding.只需先在一个字符串中迭代 List 中的内容,该字符串将在继续之前保存其值。
Just like below,就像下面一样,
List<string> hobbies = new List<string>();
string hobbies_ = "";
var hobbies = new List<string>() { };
Console.WriteLine("Please enter your name");
string myName = Console.ReadLine();
Console.WriteLine("Tell me something about you");
string myAbout = Console.ReadLine();
Console.WriteLine("What kind of hobbies do you have?");
string myHobbies = Console.ReadLine();
hobbies.Add(myHobbies);
foreach (var hobby in hobbies)
{
hobbies_ += hobbies + "\n";
}
var query = myName + '\n' + myAbout + '\n' + hobbies_;
File.AppendAllLines("C:\\test.txt", query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.