我有一个void方法。versionControl
已经预先初始化了,但我在这个方法的workspace
和versionControl
上仍然得到一个空例外。
//populate a comboBox with the available workspaces
public IEnumerable<string> GetWorkspace(string path)
{
versionControl = tpc.GetService<VersionControlServer>();
Workspace[] retVal = versionControl.QueryWorkspaces(null, versionControl.AuthorizedUser, Environment.MachineName );
foreach (Workspace w in retVal)
{
yield return w.Name;
}
}
//gets the selected workspace in the combo box from the MainForm()
public void MapWorkspace(string selectedWorkspace)
{
var workspace = versionControl.GetWorkspace(selectedWorkspace, versionControl.AuthorizedUser);
}
答案 0 :(得分:4)
由于此方法使用延迟执行(yield
)versionControl
仅在执行查询时实例化,因为它已枚举,例如使用ToList
或FirstOrDefault
:
var query = GetWorkspace(path); // versionControl is null
var workSpace = query.FirstOrDefault() // now versionControl is instantiated
由于这个原因,我不会在使用延迟执行的方法中初始化字段。
修改:以下是此行为的演示:http://ideone.com/CVwzZZ