How to Check if a Variable Exists or Not?

zenfreak

Client
Регистрация
21.08.2013
Сообщения
249
Благодарностей
11
Баллы
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.
 

Dimionix

Moderator
Регистрация
09.04.2011
Сообщения
3 068
Благодарностей
3 100
Баллы
113
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 {}
 

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