2016-10-06 6 views
0

У меня есть Hashtable под названием hash, чье первое значение является идентификатором GUID, а второе - объектом типа InstallationFiles. Я хочу быть в состоянии сделать следующее:Вытащить объект из хеш-таблицы и передать его другому объекту

InstallationFiles ifiles = (InstallationFiles)hash[objectGuid]; 

Даже если она возвращает правильное значение hash[objectGuid], я также найти запись с hash[objectGuid] как ключ в Hashtable, однако это один (InstallationFiles)hash[objectGuid] всегда возвращает нуль. Почему это может быть?

ОБНОВЛЕНИЕ.

Хорошо, я покажу больше кода. Пользователь находится в этом окне. Он/она нажимает кнопку добавления файла, чтобы добавить файл в список. enter image description here

Другое окно выскакивает: enter image description here

Когда пользователь нажимает на кнопку добавления файла в первой форме (первая картинка), следующий метод срабатывает:

Setup_Generator.cs (Моя главная форма объект, первая картинка):

private void addFileOrDirectory(string ifFileOrDirectory) 
    {    
      if (ifFileOrDirectory == "File") 
      { 
      //here I initialize the object of the second form (second picture) 
       efef = new editFileEntryForm(info.TheRightProgramFilesDirectoryUserView, info.ApplicationName, "File", null); 
      if (efef.ShowDialog() == DialogResult.OK) 
      { 
       //every file entry has a unique guid 
       Guid g = Guid.NewGuid(); 
       //efef.InstFiles is an object of type InstallationFiles (code in the next block) 
       hash.Add(g, efef.InstFiles); 
       item1 = new ListViewItem(efef.InstFiles.File); 
       item1.SubItems.Add(efef.InstFiles.DestDir); 
       listViewDerivative1.Items.AddRange(new ListViewItem[] { item1 }); 
       item1.Tag = g; 
      } 
     } 

editFileEntryForm.cs, или второй вид, изображенный на втором рисунке:

class editFileEntryForm 
    { 
    public Classes.InstallationFiles InstFiles = null; 
    //... 
    public editFileEntryForm(string instDir, string appName, string fileOrDir, Classes.InstallationFiles instFiles) 
    { 
    //... 
     if (instFiles != null) 
     { 
      InstFiles = instFiles; 
      sourceFileTextBox.Text = instFiles.File; 
      this.destinationDirComboBox.SelectedIndex = instFiles.DestinationDirSelectedIndx; 
      this.ifFileExistsComboBox.SelectedIndex = instFiles.FileExistsSelectedIndex; 
     } 
    } 
    private void okButtonClick() 
    { 
     if (FileOrDir == "File") 
     { 
      //here I initialize an object which I add to a hashtable in Setup_generator.cs 
      InstFiles = new Classes.InstallationFiles(this.sourceFileTextBox.Text, 
                 destinationDirComboBox.Text, 
                 NSISvariables[destinationDirComboBox.Text], 
                 NSISvariables[ifFileExistsComboBox.Text], 
                 ifFileExistsComboBox.SelectedIndex, 
                 destinationDirComboBox.SelectedIndex 
                ); 
      this.DialogResult = DialogResult.OK; 
      this.Hide(); 
     } 
    } 
    } 

До этого момента все идет по плану - значения сохраняются в хэш-таблице Hashtable, ключ - GUID, а значение - объект InstallationFiles. Когда пользователь выбирает въездной щелчки на редактирование в основной форме (Setup_Generator.cs или первое изображение), я следующее:

private void edit() 
    { 
     //retrieve the selected item and its GUID 
     ListViewItem lvi = listViewDerivative1.SelectedItems[0]; 
     string objectGuid = lvi.Tag.ToString(); 
     //(Classes.InstallationFiles)hash[objectGuid] returns null, even though an object with the given GUID exists in the hashtable! 
     Classes.InstallationFiles ifiles = (Classes.InstallationFiles)hash[objectGuid]; 
     //initializing a new form to edit a selected entry 
     efef = new editFileEntryForm(this.info.TheRightProgramFilesDirectoryUserView, this.info.ApplicationName, "File", ifiles); 
     if (efef.ShowDialog() == DialogResult.OK) 
     { 
      //This is my ultimate goal: replace old values with new ones in the HASHTABLE hash! 
      //not working, because hash[objectGuid] as Classes.InstallationFiles) returns as null 
      (hash[objectGuid] as Classes.InstallationFiles).File = efef.InstFiles.File; 
      (hash[objectGuid] as Classes.InstallationFiles).DestDir = efef.InstFiles.DestDir;  
      (hash[objectGuid] as Classes.InstallationFiles).DestDirNSISVariable = efef.InstFiles.DestDirNSISVariable; 
      (hash[objectGuid] as Classes.InstallationFiles).IfFileExistsNSISVariable = efef.InstFiles.IfFileExistsNSISVariable; 
     {  
     } 
     } 
+5

Показанный код вместо описания может помочь нам обнаружить ошибку. –

+4

Проблема заключается где-то в другом месте, чем вы думаете. Пожалуйста, предоставьте [mcve]. – Heinzi

+0

'var obj = hash [objectGuid]; InstallFiles ifiles = (InstallationFiles) obj; 'ifiles может быть нулевым, только если obj равно null (иначе он бы выбрал InvalidCastException) – Artiom

ответ

1

Вы звоните

efef = new editFileEntryForm(info.TheRightProgramFilesDirectoryUserView, 
     info.ApplicationName, "File", null); 

но вы проходите instFiles, как нуль

public editFileEntryForm(string instDir, string appName, string fileOrDir, Classes.InstallationFiles instFiles) 
{ 
//... instFiles - null here 
    if (instFiles != null) 
    { 
     InstFiles = instFiles; 
     sourceFileTextBox.Text = instFiles.File; 
     this.destinationDirComboBox.SelectedIndex = instFiles.DestinationDirSelectedIndx; 
     this.ifFileExistsComboBox.SelectedIndex = instFiles.FileExistsSelectedIndex; 
    } 
} 

так, когда вы звоните hash.Add(g, efef.InstFiles); вы передаете null значение, как efef.InstFiles

Вот почему у вас hashtable содержит нулевые значения.

Смежные вопросы