在void方法上使用时,Object变为null

时间:2013-11-19 08:50:18

标签: c# tfs2010

我有一个void方法。versionControl已经预先初始化了,但我在这个方法的workspaceversionControl上仍然得到一个空例外。

//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);
    }

1 个答案:

答案 0 :(得分:4)

由于此方法使用延迟执行(yieldversionControl仅在执行查询时实例化,因为它已枚举,例如使用ToListFirstOrDefault

var query = GetWorkspace(path);        // versionControl  is null
var workSpace = query.FirstOrDefault() // now versionControl is instantiated

由于这个原因,我不会在使用延迟执行的方法中初始化字段。

修改:以下是此行为的演示:http://ideone.com/CVwzZZ