How to Check if a Variable Exists or Not?

  • Автор темы Автор темы zenfreak
  • Дата начала Дата начала

zenfreak

Client
Регистрация
21.08.2013
Сообщения
249
Реакции
12
Баллы
18
I need to assign many values to different variables using the c# code:

Код:
Развернуть Свернуть Копировать
project.Variables["myVariable0"].Value = myValue0;
project.Variables["myVariable1"].Value = myValue1;
project.Variables["myVariable2"].Value = myValue2;
project.Variables["myVariable3"].Value = myValue3;
project.Variables["myVariable4"].Value = myValue4;
project.Variables["myVariable5"].Value = myValue5;

Let's say that in my project I only have myVariable0, myVariable1, myVariable2 variables and myVariable3, myVariable4, myVariable5 don't exist. Running the above code will throw an error because the last 3 variables don't exist. Is there a way to first check if the variable exists before trying to assign a value?

Something like:

Код:
Развернуть Свернуть Копировать
if (project.Variables["myVariable0"] == true){
project.Variables["myVariable0"].Value = myValue0;
}

The reason behind this is that I have many such lines and I would like to use the same block of code for any project and only assign values for variables that exist in the current project.
 
C#:
Развернуть Свернуть Копировать
if (project.Variables.Keys.Contains("myVariable0"))
    project.Variables["myVariable0"].Value = myValue0;
if (project.Variables.Keys.Contains("myVariable1"))
    project.Variables["myVariable1"].Value = myValue1;
if (project.Variables.Keys.Contains("myVariable2"))
    project.Variables["myVariable2"].Value = myValue2;
if (project.Variables.Keys.Contains("myVariable3"))
    project.Variables["myVariable3"].Value = myValue3;
if (project.Variables.Keys.Contains("myVariable4"))
    project.Variables["myVariable4"].Value = myValue4;
if (project.Variables.Keys.Contains("myVariable5"))
    project.Variables["myVariable5"].Value = myValue5;
C#:
Развернуть Свернуть Копировать
try { project.Variables["myVariable0"].Value = myValue0; } catch {}
try { project.Variables["myVariable1"].Value = myValue1; } catch {}
try { project.Variables["myVariable2"].Value = myValue2; } catch {}
try { project.Variables["myVariable3"].Value = myValue3; } catch {}
try { project.Variables["myVariable4"].Value = myValue4; } catch {}
try { project.Variables["myVariable5"].Value = myValue5; } catch {}
 
  • Спасибо
Реакции: Petr_G

Кто просматривает тему: (Всего: 0, Пользователи: 0, Гости: 0)