如何在{}上的c#中使用var
如何在{}上的c#中使用var,如:如何在{}上的c#中使用var,c#,if-statement,while-loop,var,C#,If Statement,While Loop,Var,如何在{}上的c#中使用var,如: if { var test; while { test = "12345"; //test is defined } var test2 = test; //test is undefined } 我不明白。您不能对未初始化的变量使用var,因为在这种情况下,编译器不知道真正的类型var是一种语法糖——编译器应该决定使用哪种类型,在IL代码中您将看到真实的类型 如果您确实需要var,则应使用某种
if
{
var test;
while
{
test = "12345";
//test is defined
}
var test2 = test;
//test is undefined
}
我不明白。您不能对未初始化的变量使用
var
,因为在这种情况下,编译器不知道真正的类型var
是一种语法糖——编译器应该决定使用哪种类型,在IL代码中您将看到真实的类型
如果您确实需要var
,则应使用某种类型的任何值对其进行初始化(在您的示例中为-string
):
Var不是一种类型,Var是一个关键字,告诉计算机决定哪种类型适合您的值 您可以改为使用此选项:
if
{
var test = "placeholder";
while
{
test = "12345";
//test is defined
}
var test2 = test;
//test is undefined
}
或者更好的方法是,从一开始就声明一个字符串,当您不知道在声明时需要什么类型时,可以使用var,当您知道类型时,最好使用正确的类型声明引用
编辑:
这段代码对我来说很好(请注意,在您的原始代码中,您缺少该条件)
if (true)
{
string test;
while (true)
{
test = "12345";
//test is defined
}
var test2 = test;
//test is undefined
}
您可以使用
object
类型而不是var
,然后将null
指定为初始化。它将根据您的意愿用于字符串,int
请检查以下内容:
if
{
object test = null;
while
{
test = "12345";
//test is defined
}
var test2 = test;
//test is undefined
}
请检查示例。使用
if
和而构造了它们应该如何使用。你不能,编译器不能在没有赋值的情况下推断类型。如果你真的需要,可以显式指定它,或者使用类似dynamic
的东西。你到底想用这段代码实现什么?thx,works!love u@TimerTick,您可以使用任何int
值(没有Int32.Empty
)如果我键入字符串test;它不起作用,我需要一个占位符看看我现在在答案中添加了什么,您的原始代码中有很多语法错误。@timer请注意while是一个循环,除非您的条件在某些时候变为false,否则您的程序将始终尝试将test声明为“12345”并且永远不要进行测试2=测试;
if
{
object test = null;
while
{
test = "12345";
//test is defined
}
var test2 = test;
//test is undefined
}