首先,我想说this的使用只是为了学习,可能不会在功能应用程序中使用。
我创建了一个DateHandler
接收Date
对象(自定义)的类(命名),它有一个接收字符串的函数,将每个字符更改为它的匹配项。
例如:
"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
}
我的问题:我必须为每个 new 定义一个新字典DateHandler
,并且我正在尝试一种创造性的方式,即只有一个字典指向它的匹配定义。有什么想法吗?
我的主要目标:字典的一个实例Properties
,它将用作对来自多个实例的值的引用DateHandler
。