局部变量“mydate"在访问之前可能未初始化 [英] Local variable 'mydate' might not be initialized before accessing
问题描述
在我的代码中,我像这样初始化了日期时间
In my code i initilized Datetime like this
DateTime myDate;
但是当我尝试访问它时,我收到了这个错误.
But when i try to access it then i got this error.
局部变量myDate"在访问之前可能没有被初始化
Local variable 'myDate' might not be initialized before accessing
这里我初始化了我的日期知道吗?
Here i initialized my date know ?
推荐答案
你声明它,但你没有给它一个值;你不能读取一个局部变量,直到它被明确分配".举个简单的例子:
You declared it, but you didn't give it a value; you can't read a local variable until it is "definitely assigned". For a simple example:
DateTime myDate = DateTime.UtcNow; // is assigned
您不必立即赋予它一个值...您可以在尝试阅读它之前的任何时间赋予它一个值,包括任何分支等,只要它有一个值就不会产生歧义,例如:
You don't have to give it a value right away... you can give it a value any time before you try to read it, including any branching etc that leaves no ambiguity that it has a value, for example:
DateTime myDate;
//....
if(condition) {
myDate = DateTime.UtcNow;
} else {
myDate = GetDateFromSomewhereElse();
}
Console.WriteLine(myDate);
相比之下,字段(类变量)会自动初始化为它们的全零值,并且从对象的创建开始就被视为明确赋值".
For contrast, fields (class variables) are automatically initialized to their all-zero value, and are treated as "definitely assigned" from the object's creation.
这篇关于局部变量“mydate"在访问之前可能未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!