在C#中有没有类似于PHP isset()的东西? [英] Is there anything similar to PHP isset() in C#?
问题描述
您好,
我来自PHP背景,想知道是否有办法检查变量是否存在,如果没有创建它。
与下面的PHP代码中看到的类似。
Hi There,
I come from a PHP background and would like to know if there's a way to check if a variable exists, and if not create it.
Something similar as seen in the the PHP code below.
if(isset($variable)){
echo 'variable is set';
}else{
echo 'variable is not set';
$variable = 'This variable is now set';
}
目前我收到错误在声明之前不能使用局部变量'pricelist'。请记住,这是一个C#控制台应用程序,而不是基于Web的应用程序。
问候,
我尝试了什么:
在线研究,但遗憾的是找不到任何东西。
Currently I am getting the error "Cannot use local variable 'pricelist' before it is declared". Keep in mind this is a C# console application, not a web based app.
Regards,
What I have tried:
Online research but could not find anything unfortunately.
推荐答案
variable)){
echo'variable is set';
}其他{
echo'变量未设置';
variable)){ echo 'variable is set'; }else{ echo 'variable is not set';
variable ='此变量现已设置';
}
variable = 'This variable is now set'; }
目前我收到错误在声明之前不能使用局部变量'pricelist'。请记住,这是一个C#控制台应用程序,而不是基于Web的应用程序。
问候,
我尝试了什么:
在线研究,但遗憾的是找不到任何东西。
Currently I am getting the error "Cannot use local variable 'pricelist' before it is declared". Keep in mind this is a C# console application, not a web based app.
Regards,
What I have tried:
Online research but could not find anything unfortunately.
在C#中所有变量必须在使用前声明:
In C# all variables must be declared before they are used:
string variable = null; // <- declaration
if(variable != null)
{
Console.WriteLine("variable is set");
}
else
{
Console.WriteLine("variable is not set");
variable = "This variable is now set";
}
但前面的例子有点傻。我们假设您有一个方法,并且您想测试一个参数:
But the previous example is a bit silly. Let's assume you have a method and you want to test an argument:
public void Run(string variable)
{
if(variable != null)
{
Console.WriteLine("variable is set");
}
else
{
Console.WriteLine("variable is not set");
}
}
无论如何,变量必须在您第一次使用之前存在。 C#强制您显式初始化所有局部变量。另一方面,类的成员字段获得默认值,因此这将起作用:
In any case the variable must exist before you first use it. And C# forces you to initialize all local variables explicitly. On the other hand member fields of a class get default values assigned so this will work:
class Test
{
private string variable;
public void Run()
{
if(variable != null)
{
Console.WriteLine("variable is set");
}
else
{
Console.WriteLine("variable is not set");
variable = "This variable is now set";
}
}
}
这篇关于在C#中有没有类似于PHP isset()的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!