我想将当前日期返回到我的事件记录器,我试过这个:
public class LogDate
{
protected DateTime localDate { get; set; }
public LogDate()
{
localDate = DateTime.Now;
}
}
public class Eventlog : LogDate
{
public void logEvent(string answer)
{
this.localDate = new DateTime();
try
{
string sSource;
string sLog;
string sEvent;
sSource = "dotNET Sample App";
sLog = "filmdatabase";
sEvent = this.localDate + answer;
不知何故,当我尝试这个时,它返回1-1-0001 00:00:00。而不是实际的时间。
答案 0 :(得分:3)
您再次为新this.localDate
指定DateTime
:
this.localDate = new DateTime();
1-1-0001 00:00:00
是new DateTime()
的默认值。要解决此问题,请使用this.localDate
,而无需使用new DateTime()
重新分配。
public class Eventlog : LogDate
{
public void logEvent(string answer)
{
//this.localDate = new DateTime(); //remove this
try
{
string sSource;
string sLog;
string sEvent;
sSource = "dotNET Sample App";
sLog = "filmdatabase";
sEvent = this.localDate.ToString() + " " + answer; //use it directly as you have initialized that in your constructor
直接使用它,因为您始终在构造函数中初始化它:
public class LogDate
{
protected DateTime localDate { get; set; }
public LogDate()
{
localDate = DateTime.Now;
}
}
答案 1 :(得分:1)
您将localDate
设置为新的默认值
this.localDate = new DateTime();