猿问

有什么办法欺骗编译器允许这样做吗?

我有一个XAML工作流程,相当于


Bar bar;


if (foo.SomeFlag)

{

    // ... do stuff


    bar = .. // set bar, guaranteed unless exception thrown earlier in this block

}


// do other stuff 


// here it is guaranteed that foo.SomeFlag is the same as it was before

if (foo.SomeFlag)

{

   // use bar

}

在普通的C#中,我如何尝试重写它。问题是我遇到Use of unassigned variable 'bar' ..编译器错误。我了解错误,但是我认为我可以通过编写文字来克服错误


Bar bar;


const bool someFlag = foo.SomeFlag;


if (someFlag)

{

    // ... do stuff


    bar = .. // set bar, guaranteed unless exception thrown earlier in this block

}


// do other stuff 


if (someFlag)

{

   // use bar

}

但显然这不是有效的语法。


任何想法如何克服?


慕斯709654
浏览 120回答 3
3回答

慕桂英546537

编译器要求bar在使用它之前将其设置为某个值,并且由于someFlag可能在您的if块之间进行更改(这意味着第一个块可能无法运行,而第二个块可能会运行),因此它将给您带来错误。为避免这种情况,您可以最初将bar设置为默认值:Bar bar = default(Bar);   // this will be 'null' for class objects然后您的其余代码应按预期工作const bool someFlag = foo.SomeFlag;if (someFlag){    // Do something, assign bar to new value    bar = new Bar();}// Do some other stuff // Possibly add a check that bar was set, just to be safe...if (someFlag && bar != null){    // Use bar    bar.DoSomething();}

慕尼黑的夜晚无繁华

欺骗编译器允许这样做意味着您的解决方案将有机会出现异常。想想,如果foo.SomeFlag不正确怎么办?bar的值将为null,或更具体地说,它将为default(Bar)。(是的,编译器知道任何类型的默认值是什么)。如果按照我的想法,Bar是一个类,则该值肯定为null。然后当它尝试使用bar时,假设您尝试使用bar,它会引发异常。编译器实际上是在保护您免受它侵害。解决的方法只是在使用bar之前进行空检查。喜欢:if (someFlag){&nbsp; &nbsp;if(bar != null)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;// use bar&nbsp; &nbsp;}}尽管如此,我强烈建议您开始初始化变量,这样您就可以肯定并且不会忘记。喜欢:解决方案1:用一些东西开始吧。Bar bar = null; // <- Only if you know for sure Bar is a class// orBar bar = default(Bar);if (foo.SomeFlag){&nbsp; &nbsp; ...}解决方案2:另辟else径if (foo.SomeFlag){&nbsp; &nbsp;...}else{&nbsp; &nbsp; bar = null; // <- Only if you know for sure Bar is a class&nbsp; &nbsp; // or&nbsp; &nbsp; bar = default(bar);}...

子衿沉夜

编译器不够智能,无法识别您的if块是否将被实际执行。因此,它假定bar在使用之前可能无法初始化。为了减轻这种情况,只需将bar初始值设置为null或提供一条else语句即可。Bar bar = null;const bool someFlag = foo.SomeFlag;if (someFlag){&nbsp; &nbsp; // ... do stuff&nbsp; &nbsp; bar = .. // set bar, guaranteed unless exception thrown earlier in this block}// do other stuff&nbsp;if (someFlag){&nbsp; &nbsp;// use bar}或者:Bar bar;const bool someFlag = foo.SomeFlag;if (someFlag){&nbsp; &nbsp; // ... do stuff&nbsp; &nbsp; bar = .. // set bar, guaranteed unless exception thrown earlier in this block}else{&nbsp; &nbsp; bar = null;}// do other stuff&nbsp;if (someFlag){&nbsp; &nbsp;// use bar}
随时随地看视频慕课网APP
我要回答