可能重复:
Why do I have to assign a value to an int in C# when defaults to 0?我真的必须给我的所有变量初始值吗?
我刚开始写所谓的杂志一个人为的应用学习C#。在解析日志文件的函数中,我声明了变量DateTime currentEntryDate
。直到达到定义新条目的行时,它才会获得价值。 秒当我到达输入行时,该变量将用于为上一个条目创建类JournalEntry
的实例。
的问题是,对于变量的使用代码将无法编译:
使用未分配的局部变量的“currentEntryDate”
这是没有意义的我。为了保持编译器的快乐,我真的必须为变量赋予一个浪费的初始值吗?当然,我误解了某些东西,或者在我的代码中存在错误。
Pastebin上的代码:Journal.cs。我已经强调了相关的路线。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace Journal
{
class Journal
{
public List<JournalEntry> Entries;
private static readonly string EntryLineRegex =
@"-- Entry: (?<title>.*) \((?<year>\d{4})-(?<month>\d{2})" +
@"-(?<day>\d{2})\)";
public static Journal FromFile(string filePath)
{
Journal returnValue = new Journal();
StreamReader fileReader = new StreamReader(filePath);
// Prepare variables for parsing the journal file.
bool hitFirstEntry = false;
DateTime currentEntryDate;
string currentEntryTitle;
StringBuilder currentEntryText = new StringBuilder();
// Prepare a regular expression for the entry lines.
Regex entryLineRegex = new Regex(EntryLineRegex);
while (!fileReader.EndOfStream)
{
string line = fileReader.ReadLine();
if (line.StartsWith("--"))
{
// Is this the first entry encountered? If so, don't try to
// process the previous entry.
if (!hitFirstEntry)
{
hitFirstEntry = true;
}
else
{
// Create a JournalEntry with the current entry, then
// reset for the next entry.
returnValue.Entries.Add(
new JournalEntry(
currentEntryText.ToString(), currentEntryDate
)
);
currentEntryDate = new DateTime();
currentEntryText.Clear();
}
// Extract the new entry title and date from this line and
// save them.
Match entryMatch = entryLineRegex.Match(line);
GroupCollection matches = entryMatch.Groups;
currentEntryDate = new DateTime(
Convert.ToInt16(matches["year"].Value),
Convert.ToInt16(matches["month"].Value),
Convert.ToInt16(matches["day"].Value)
);
currentEntryTitle = matches["title"].Value;
}
else
{
currentEntryText.Append(line);
}
}
return returnValue;
}
}
class JournalEntry
{
public string Text;
public DateTime EntryDate;
public JournalEntry(string text, DateTime entryDate)
{
this.Text = text;
this.EntryDate = entryDate;
}
}
}
不可以,但有效的代码*必须*分配所有本地变量被访问前值和编译器*必须*保证这个的。我确信这是重复的。 – 2013-01-20 08:45:34
@pst:我如何保证编译器的? – Hubro
这是编译器确保在变量没有值之前不使用变量的方法。编译器无法从你复杂的条件语句中判断出'currentEntryDate'在你使用它之前会有一个值,所以它会抛出错误。在这里为'currentEntryDate'赋予一个初始值如此悲剧? – JLRishe