【发布时间】:2013-01-03 13:57:23
【问题描述】:
可能重复:
Why do I have to assign a value to an int in C# when defaults to 0?
我刚开始通过编写一个名为 Journal 的人为应用程序来学习 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;
}
}
}
【问题讨论】:
-
没有。但有效代码必须在所有局部变量被访问之前为其分配一个值,并且编译器必须保证这一点。我确定这是重复的。
-
@pst:那我怎么保证编译器的呢?
-
这是编译器确保在变量有值之前不使用变量的方法。编译器无法从您复杂的条件语句中确定
currentEntryDate在您使用它之前会有一个值,因此它会抛出该错误。在这里给currentEntryDate一个初始值是悲剧吗? -
@pst:你为什么把这个问题选为与Why do I have to assign a value to an int in C# when defaults to 0 重复的问题?这是一个完全不同的问题,应该得到不同的答案。
标签: c#