在声明之前不能使用局部变量DateTime?

时间:2014-01-13 10:06:29

标签: c# datetime compiler-errors

我想在Main方法的Console应用程序中获取当前的DateTime,但是我得到编译器错误“在声明之前不能使用局部变量DateTime”。以下是代码的一部分......

static void Main(string[] args)
{
       StringBuilder RequestString = new StringBuilder();
       string MachineID = "17";
       DateTime CT = DateTime.Now;
       string DateTime = CT.ToShortDateString();
       RequestString.Append(MachineID);
       RequestString.Append("|");
       RequestString.Append(DateTime);
       RequestString.Append("|");
}

4 个答案:

答案 0 :(得分:11)

变化:

string DateTime = CT.ToShortDateString();

为:

string dateTime = CT.ToShortDateString();

您不能将DateTime用作变量名。

编辑: 因为@user2864740 mentioned错误是因为变量DateTime是阴影DateTime类型,并且编译器认为OP在字符串变量Now上调用属性DateTime

答案 1 :(得分:0)

此行错误

string DateTime = CT.ToShortDateString();

你没有给它一个局部变量名,如:

string ctShortDate =  CT.ToShortDateString();

答案 2 :(得分:0)

为什么使用DateTime作为变量名? 我认为这不是一个好习惯。

DateTime CT = DateTime.Now;
string currentdate = CT.ToShortDateString();

答案 3 :(得分:0)

您可以在使用类DateTime的同一行中声明DateTime,该类会隐藏您选择的变量名称。

您可以通过变量名更改为dateTime(例如)您使用的所有位置,而不是编译和运行。尝试使用此代码:

static void Main(string[] args)
{
    StringBuilder RequestString = new StringBuilder();
    string MachineID = "17";
    DateTime CT = DateTime.Now;
    string dateTime = CT.ToShortDateString();
    RequestString.Append(MachineID);
    RequestString.Append("|");
    RequestString.Append(dateTime);
    RequestString.Append("|");
}