【问题标题】:How can i use a var in c# over {}我如何在 c# 中通过 {} 使用 var
【发布时间】:2017-10-28 11:30:38
【问题描述】:

如何在 c# 中通过 {} 使用 var,例如:

if
{
   var test;
   while
   {
      test = "12345";
      //test is defined
   } 
   var test2 = test;
   //test is undefined
}

我不明白。

【问题讨论】:

  • 使用if 和while 构造它们应该如何使用。
  • 你不能,编译器不能在没有赋值的情况下推断出类型。如果你真的需要,要么明确指定它,要么使用dynamic 之类的东西
  • 你到底想用这段代码完成什么?

标签: c# if-statement while-loop var


【解决方案1】:

您不能将var 与未初始化的变量一起使用,因为在这种情况下编译器不会知道真正的类型。 var 是语法糖——编译器应该决定使用哪种类型,在 IL 代码中你会看到真正的类型。

如果你真的想要var,你应该用某种类型的任何值初始化它(在你的情况下 - string):

if
{
   var test = String.Empty; // initialize it - now compiler knows type
   while
   {
      test = "12345";
      //test is defined
   } 
   var test2 = test;
   //test is undefined
}

【讨论】:

  • 谢谢,工作!爱你
  • @TimerTick,您可以使用任何int 值(没有Int32.Empty)
【解决方案2】:

您可以使用object 类型而不是var 然后分配null 作为初始化。如您所愿,它将适用于string, int。

请检查以下内容:

if
{
    object test = null;
    while
    {
        test = "12345";
        //test is defined
    } 
    var test2 = test;
    //test is undefined
}

请查看DotNetFiddle中的示例。

【讨论】:

    【解决方案3】:

    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
                    }
    

    【讨论】:

    • 如果我输入字符串测试;它不起作用,我需要一个占位符
    • 看看我现在添加到答案中的内容,您的原始代码中有很多语法错误。
    • @TimerTick 请注意,while 是一个循环,除非您的条件在某些时候变为 false,否则您的程序将始终尝试将 test 声明为“12345”并且永远不会继续 test2=测试;
    猜你喜欢
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多