Bas*_*mme 15 .net datetime structure
为什么是DateTime结构而不是可继承的类?
(我希望能够覆盖ToString()方法,但我不能.)
Rub*_*ben 17
可能是因为它被视为一个小的,简单且不可变的数据结构,很像整数或小数.在这些条件下使其成为结构使得使用DateTime非常有效.如果它已成为一个类,那么这种效率优势就会丢失,因为每次创建一个新的DateTime时都需要内存分配.
此外,你能想出多少种DateTime的变体形式?(忽略你想到的备用ToString实现.)它不是一个邀请多态的类型.
请注意,对于DateTimes使用不同的格式化策略,我认为你想要的,你最好看一种不同的格式,而不仅仅是使用ToString.如果查看MSDN 中的ICustomFormatter接口,您将看到如何插入String.Format管道以覆盖格式而无需对现有类型进行子集化.
Ral*_*ine 13
您可以使用扩展方法:声明扩展名:
public static class DateTimeExtensions
{
public static string ToStringFormatted(this DateTime date)
{
return date.ToString("{d}");
}
}
Run Code Online (Sandbox Code Playgroud)
使用扩展名:
using DateTimeExtensions;
...
var d = new DateTime();
System.Diagnostics.Debug.WriteLine(d.ToStringFormatted());
Run Code Online (Sandbox Code Playgroud)
这样您就可以简单地实现自己在DateTime上使用的方法.这样,它可以轻松地在您的解决方案中随处使用.您唯一需要做的就是使用命名空间.
参考:扩展方法(c#)
如果您想了解有关系统类和结构的更多信息,请下载免费的.NET反射器(http://www.red-gate.com/products/reflector/).
无论如何,如果要覆盖DateTime的格式,请提供自己的IFormatProvider.使用.NET Reflector了解DateTimeFormatInfo的实现方式,然后实现自己的.
仅仅因为它是一个结构(或者即使它是一个密封的类),这并不意味着它是道路的终点.您可以使用合成而不是继承来解决此问题.这是一个'客观化'DateTime类的例子:
public class MyDateTime
{
DateTime? value;
public MyDateTime()
{
this.Value = DateTime.Now;
}
public MyDateTime(DateTime? dateTime)
{
this.Value = dateTime;
}
public override String ToString()
{
if (this.Value != null)
{
return this.Value.Value.Month.ToString() + " my favorite time of the year";
}
return null;
}
public System.DateTime? Value
{
get { return this.value; }
set { this.value = value; }
}
}
Run Code Online (Sandbox Code Playgroud)