将我的类型转换为字符串

时间:2017-09-07 06:12:26

标签: c# persian persian-calendar

我有一个班级:

public class PersianDate
{
    public int Year;
    public int Month;
    public int Day;
    public int Hour;
    public int Minute;
    public int Second;
    public string MonthName;
}

我希望如果我像这里一样转换它:

HTools.PersianDate pDate=new HTools.PersianDate();
string date = pDate.ToString();

我希望约会:

  

1396-06-14T19:17:38

我该怎么做?

2 个答案:

答案 0 :(得分:2)

public class PersianDate
{
    public int Year;
    public int Month;
    public int Day;
    public int Hour;
    public int Minute;
    public int Second;
    public string MonthName;

    public override string ToString()
    {
        return string.Format("{0}-{1}-{2}T{3}:{4}:{5}",Year,Month,Day,Hour,Minute,Second);
    }
}

ToString()类覆盖object方法以获取所需的格式。

DotNetFiddle Example.

答案 1 :(得分:0)

如果你想要一个表示对象的字符串作为json,你可以使用“Newtonsift.Json”Nuget包:

PersianDate thing = new PersianDate();
//TODO: fill you thing with the data you need
string json = JsonConvert.SerializeObject(thing);

如果你想要特定的字符串 - ovverride你的类中的ToString方法:

public override string ToString()
{
     return $"{Year}-{Month}-{Day}T{Hour}:{Minute}:{Second}";
}