C# 将模型数据转换为字符串
如何在C#中将模型项转换为一个字符串 现在我想这样做,把IEnumerable的第一行变成一个句子C# 将模型数据转换为字符串,c#,string,model,C#,String,Model,如何在C#中将模型项转换为一个字符串 现在我想这样做,把IEnumerable的第一行变成一个句子 string xyz = test.First().toString(); 我想xyz to=“这是一个造一句话的测试”这是ToString方法可重写的原因之一。 您只需在类的模型中重写ToString()并返回您想要的任何内容 public class myModel { public string Item1 {get;set;} public string Item2 {g
string xyz = test.First().toString();
我想xyz to=“这是一个造一句话的测试”这是ToString方法可重写的原因之一。
您只需在类的模型中重写ToString()并返回您想要的任何内容
public class myModel
{
public string Item1 {get;set;}
public string Item2 {get;set;}
public string Item3 {get;set;}
public override string ToString()
{
return string.Join(" ", this.Item1, this.Item2, this.Item3);
}
}
....
myModel m = new myModel()
{
Item1 = "This is",
Item2 = "a test",
Item3 = "to make one sentence"
};
Console.WriteLine(m.ToString());
如果不列出每个项,有没有办法做到这一点?使用反射,但这将非常昂贵,而且可能不值得付出努力,因为模型中的项与ToString()重写一起,也可以看到相关的重复项,如和
string xyz = test.First().toString();
public class myModel
{
public string Item1 {get;set;}
public string Item2 {get;set;}
public string Item3 {get;set;}
public override string ToString()
{
return string.Join(" ", this.Item1, this.Item2, this.Item3);
}
}
....
myModel m = new myModel()
{
Item1 = "This is",
Item2 = "a test",
Item3 = "to make one sentence"
};
Console.WriteLine(m.ToString());