简体   繁体   English

C#检查条件后初始化变量

[英]C# initialize variable after checking a condition

I need to use a variable initialized only after checking a condition. 我只需要使用检查条件后初始化的变量。
I get the error: 我得到错误:

Use of unassigned local variable 使用未分配的局部变量

Does not the compile check if the conditions are the same? 编译是否不检查条件是否相同?
This is my code. 这是我的代码。 How can I solve it? 我该如何解决?

Web web;
if (myCondition){
    //heavy operation
    web = site.openWeb();
}

for ( n loop)
{
    //do stuff
    if (myCondition){
        //use web
    }
}

if (myCondition){
    web.Dispose()
}

Simply set it to null to make sure it is initialized at all: 只需将其设置为null即可确保它已初始化:

Web web = null;

And then, when disposing, better check that variable is not null, to make sure you dispose always when necessary: 然后,在进行处置时,最好检查变量是否为null,以确保始终在必要时进行处置:

if (web != null){
    web.Dispose();
}

Also note that you won't all Dispose if an exception is thrown in the loop. 另请注意,如果在循环中引发异常,则不会全部“ Dispose ”。 So you might want to wrap it all in try/finally. 因此,您可能希望将其全部包装在try / final中。

But as it already came that far - have you considered using ? 但是,既然已经走了那么远-您是否考虑过使用

Try something like this: 尝试这样的事情:

Web web =  null;
if (myCondition)
{
    //heavy operation
    web = site.openWeb();
}

for ( n loop)
{
    //do stuff
    if (myCondition)
    {
        //use web
    }
}

if (myCondition)
{
    web.Dispose()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM