【问题标题】:Turn model data into string [duplicate]将模型数据转换为字符串 [重复]
【发布时间】:2017-02-14 12:34:39
【问题描述】:

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

IEnumerable<MyModel> test = _table.entity.ToMyModel();

现在我的模型是这样的

return new myModel
{
    Item1 = "This is ",
    Item2 = " a test ",
    Item3 = " to make one sentence"
}

现在我想做这样的事情来将 IEnumerable 的第一行变成一个句子。

string xyz = test.First().toString(); 

我想让xyz=“这是一个造句的测试”

【问题讨论】:

标签: c# string model


【解决方案1】:

这是 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() 覆盖一起努力
猜你喜欢
  • 1970-01-01
  • 2019-10-27
  • 2016-09-06
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多