使用try/catch使得我无法在try/catch块之外使用变量

sk0*_*099 0 c# scope try-catch

我有一个Product从Web服务获取对象的代码.如果没有产品,则返回EntityDoesNotExist异常.我需要处理这个..但是,我有很多其他代码处理返回Product,但如果此代码不在try/catch中,它不起作用,因为Product基本上没有定义.是否唯一的方法是将其他相关代码包含在try/catch中?这看起来真的很草率.

代码示例:

try {
    Product product = catalogContext.GetProduct("CatalogName", "ProductId");

} catch(EntityDoesNotExist e) {
    // Do something here
}

if(dataGridView1.InvokeRequired) {
    // Do something in another thread with product
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ter 8

只需在try/catch范围之外声明它.

Product product;
try
{
    product = catalogContext.GetProduct("CatalogName", "ProductId");
}
catch (EntityDoesNotExist e)
{
    product = null;
}

if (dataGridView1.InvokeRequired)
{
    // use product here
}
Run Code Online (Sandbox Code Playgroud)

  • 使用这个,之后我尝试执行“MessageBox.Show(p.SomeProperty)”,它显示:使用未分配的局部变量“p” (3认同)
  • @StephenKnoth你必须在`try`之前指定`product`一些值(例如`Product product = null;`),或者在`catch`中指定(如此解决方案所有),或者让`catch`总是`throw`再次,不是*只*在`try`中分配它.`try`中的东西被视为可能会运行,而不是它们会运行,所以`p`可能在该上下文中被取消分配. (2认同)