c# - 无法将类型 'string' 隐式转换为 'System.DateTime' - 使用 t
问题描述
如下所示,该错误源于我认为从 Visual Basic 转换为 C# 之间的错误。我不知道这是否是与 VB 的不正确/过时链接,或者我正在“转换”为时间值的“字符串”。在我是否必须更改 if-then 语句的结构方面需要帮助。
using System;
using System.Media;
using System.Windows.Forms;
namespace NotificationDemo
{
public partial class NotificationDemo : Form
{
public NotificationDemo()
{
InitializeComponent();
}
// Variables //
public int hour;
public int minute;
// Messaging System //
public void Alert(string msg)
{
NotifyForm frmn = new NotifyForm();
frmn.showAlert(msg);
}
private void BtnNotify_Click(object sender, EventArgs e)
{
this.Alert("Default Message");
SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"C:\Windows\Media\Alarm03.wav";
player.Play();
}
// Basic Schedule SysFunction
public string currenttime;
public string messagetime;
private void timer1_Tick(object sender, EventArgs e)
{
currenttime = DateTime.Now.ToString("hh:mm:ss tt");
label1.Text = currenttime;
}
private void timer2_Tick(object sender, EventArgs e)
{
messagetime = maskedTextBox1.Text + " " + comboBox1.Text;
if (currenttime == messagetime)
{
timer2.Stop();
this.Alert(textBox1.Text);
button1.Enabled = true;
button2.Enabled = false;
SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"C:\Windows\Media\Alarm03.wav";
player.Play();
}
}
private void button1_Click(object sender, EventArgs e)
{
timer2.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer2.Stop();
button1.Enabled = true;
button2.Enabled = false;
}
// Advanced Schedule SysFunction
public ProgramFunctionsDataContext doAction = new ProgramFunctionsDataContext();
private void NotificationDemo_Load(object sender, EventArgs e)
{
// // Basic Component
int hour = 1;
int minute = 1;
for (this.hour = hour; hour <= 12; hour++)
{
cbhour.Items.Add(hour);
}
for (this.minute = minute; minute <= 59; minute++)
{
cbminute.Items.Add(minute);
}
// Appointment Check
foreach (var app in doAction.AppointmentSets)
{
///LINE OF ERROR
if (app.AppointmentDate = DateTime.Today.ToLongDateString())
///LINE OF ERROR
{
}
}
}
}
}
解决方案
这是由于您正在使用=
which 是分配值的运算符
相反,您需要使用==
对if
语句进行比较
更新:由于@Llama担心以前的解决方案会导致转换错误并且我误解了错误消息,因此可以使用以下两种解决方案:
方案一:直接根据Date比较
if (app.AppointmentDate.Date == DateTime.Today.Date)
解决方案 2:将string
格式中的日期与 on进行比较ToLongDateString()
if (app.AppointmentDate.ToLongDateString() == DateTime.Today.ToLongDateString())
解决方案 1 将是首选,因为它更简单并且与解决方案 2 完全相同
在进行比较时,如果将其转换为格式,请确保使用的两个值必须是相同的数据类型和Date
字符串String
格式。
推荐阅读
- r - 如何在R中找到散点图的细胞倍增时间?
- php - Laravel 多对多关系在一个模型上失败,但在另一个模型上失败
- api - 检测vue组件完成渲染
- ocr - OCR 将 E 检测为 £
- amazon-web-services - ssh ec2 密钥错误权限被拒绝(公钥)
- odata - 如何将 Odata 请求转换为 JSON 响应
- java - 从一个 java 文件中的一个 ArrayList 中提取数据,并将其显示在 ArrayList 中的不同 java 文件中
- laravel - Facade\Ignition\Exceptions\ViewException count():参数必须是数组或者实现了Countable的对象(View:
- javascript - jws API 的异步版本有什么好处?
- mysql - Mysql Group By不求和值