C#在if/else中使用构造函数

C#在if/else中使用构造函数,c#,C#,当我按如下方式编写代码时,当它计算毫秒时,DateTime对象Ende在行中不存在(根据intellisense)。为什么该代码不正确,然后如何正确使用构造函数 private void timer2_Tick(object sender, EventArgs e) { //Take image and analyse for radius Capture_Image(); Measure_Circle(); //stop

当我按如下方式编写代码时,当它计算毫秒时,
DateTime
对象
Ende
在行中不存在(根据intellisense)。为什么该代码不正确,然后如何正确使用构造函数

private void timer2_Tick(object sender, EventArgs e)
    {
        //Take image and analyse for radius
        Capture_Image();
        Measure_Circle();
        //stop timer
        timer2.Stop();
        //Same code as when button13 is clicked
        DateTime Start = DateTime.Now;

        if(DateTime.Now.ToString("tt") == "AM")
        {
            DateTime Ende = new DateTime(Start.Year, Start.Month, Start.Day, 12, 20, 0);
        }
        else
        {
            DateTime Ende = new DateTime(Start.Year, Start.Month, Start.Day + 1, 0, 20, 0);
        }

        int dauer = (int)(Ende - Start).TotalMilliseconds;
        label32.Text = DateTime.Now.AddMilliseconds(dauer+100).ToString();

        label28.Text = DateTime.Now.ToString();

        timer2.Interval = dauer;
        timer2.Start();
    }

在if语句外部定义
Ende
,并在内部赋值。试试看:

....
DateTime Ende = new DateTime();
if(DateTime.Now.ToString("tt") == "AM")
{
  Ende = new DateTime(Start.Year, Start.Month, Start.Day, 12, 20, 0);
}
else
{
  Ende = new DateTime(Start.Year, Start.Month, Start.Day + 1, 0, 20, 0);
}
这样:

private void timer2_Tick(object sender, EventArgs e)
{
    //Take image and analyse for radius
    Capture_Image();
    Measure_Circle();
    //stop timer
    timer2.Stop();
    //Same code as when button13 is clicked
    DateTime Start = DateTime.Now;
    DateTime Ende;
    if(DateTime.Now.ToString("tt") == "AM")
    {
        Ende = new DateTime(Start.Year, Start.Month, Start.Day, 12, 20, 0);
    }
    else
    {
        Ende = new DateTime(Start.Year, Start.Month, Start.Day + 1, 0, 20, 0);
    }

    int dauer = (int)(Ende - Start).TotalMilliseconds;
    label32.Text = DateTime.Now.AddMilliseconds(dauer+100).ToString();

    label28.Text = DateTime.Now.ToString();

    timer2.Interval = dauer;
    timer2.Start();
}

只需声明
DateTime-Ende。发生此错误的原因是变量范围

您无法访问声明变量所在范围之外的变量。在if
if(Start.Hour<12)之外声明它应该比将其转换为字符串并与
“AM”
进行字符串比较更有效,您可以去掉整个
if
对象,并使用三元运算符创建
Ende
date:
DateTime Ende=Start.date.AddHours(Start.Hour<12?12:24)
这是因为
Date
属性只返回日期部分(时间设置为0),然后我们可以将
12
24
小时添加到该部分,具体取决于
Start
是否在中午之前。无需指定
Ende
值,它无论如何都会被覆盖。