Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将模型数据转换为字符串_C#_String_Model - Fatal编程技术网

C# 将模型数据转换为字符串

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

如何在C#中将模型项转换为一个字符串

现在我想这样做,把IEnumerable的第一行变成一个句子

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());