1
首先,我想说的是,这只用于学习,并且可能不会在功能应用中使用。c#自定义日期类,字符串格式
我创建了一个接收对象Date
(自定义)类(名为DateHandler
),它具有接收一个串,改变每个字符是匹配的功能。
例如:
"d/m/Y"
可以返回"1/1/2005"
d => Day
m => Month
Y => Full Year
请注意,不是预先定义的字符将不会被改变。
的Date
类:
class Date
{
#region Properties
private int _Day;
private int _Month;
public int Day
{
get
{
return _Day;
}
set
{
if (value < 1)
throw new Exception("Cannot set property Date.Day below 1");
this._Day = value;
}
}
public int Month
{
get
{
return _Month;
}
set
{
if (value < 1)
throw new Exception("Cannot set property Date.Month below 1");
this._Month = value;
}
}
public int Year;
#endregion
#region Ctors
public Date() { }
public Date(int Day, int Month, int Year)
{
this.Day = Day;
this.Month = Month;
this.Year = Year;
}
#endregion
}
的DateHandler
类:
class DateHandler
{
#region Properties
private Date Date;
private Dictionary<char, string> Properties;
private int Properties_Count;
#endregion
#region Ctors
public DateHandler()
{
Properties = new Dictionary<char, string>();
}
public DateHandler(Date Date)
: this()
{
this.SetDate(Date);
}
#endregion
#region Methods
public void SetDate(Date Date)
{
this.Date = Date;
this.SetProperties();
}
private void SetProperties()
{
this.Properties.Add('d', this.Date.Day + "");
this.Properties.Add('m', this.Date.Month + "");
this.Properties.Add('Y', this.Date.Year + "");
this.Properties.Add('y', this.Date.Year.ToString().Substring(Math.Max(0, this.Date.Year.ToString().Length - 2)));
this.Properties_Count = Properties.Count;
}
public string Format(string FormatString)
{
int len = FormatString.Length;
if (Properties.ContainsKey(FormatString[0]))
{
FormatString = FormatString.Replace(FormatString[0] + "", this.Properties[FormatString[0]] + "");
}
for (int i = 1; i < len; i++)
{
if (this.Properties.ContainsKey(FormatString[i]) && FormatString[i - 1] != '\\')
{
FormatString = FormatString.Replace(FormatString[i] + "", this.Properties[FormatString[i]] + "");
}
}
return FormatString;
}
#endregion
}
我的问题:我必须定义一个新的字典,每一个新的DateHandler
,我试图想一种创造性的方式,那就是只有一个字典会指向它的匹配定义。任何想法如何?
我的主要目标:字典Properties
,这将被用作从DateHandler
多个实例参考值的一个实例。
只是为了澄清,你试图让所有条目(例如'd',this.Date.Day +“”)的一个词典实例(例如'属性'词典) DateHandler'会引用?请让我知道,如果我的方式:) – 2012-08-02 02:29:25
是否有一个特定的原因,你不只是存储'DateTime'和使用内置的字符串格式函数已经存在于.NET框架? – 2012-08-02 02:35:22
@Layoric正是。 – Novak 2012-08-02 02:38:08