gpt4 book ai didi

c# - 像这样使用嵌套的 Try..Catch block 不好吗?

转载 作者:行者123 更新时间:2023-11-30 19:04:00 28 4
gpt4 key购买 nike

这是个坏主意吗?有没有更好的方法达到同样的效果?

// assume that "name" is a string passed as a parameter to this code block
try
{
MainsDataContext dx = new MainsDataContext();
try
{
Main m = dx.Main.Single(s => s.Name == name);
return m.ID;
}
catch (InvalidOperationException)
{
Guid g = Guid.NewGuid();

Main s = new Main
{
Name = name,
ID = g
};

dx.Mains.InsertOnSubmit(s);
dx.SubmitChanges();

return g;
}
}
catch (Exception ex)
{
// handle this
}

此处的目标是获取记录的 ID(如果存在),否则创建该记录并返回其 ID。

最佳答案

您应该使用 SingleOrDefault,这样如果记录不存在,它将返回类的默认值 null。

MainsDataContext dx = null;    
try
{
dx = new MainsDataContext();

Main m = dx.Main.SingleOrDefault(s => s.Name == name);

if ( m == null)
{
Guid g = Guid.NewGuid();

m = new Main
{
Name = name,
ID = g
};

dx.Mains.InsertOnSubmit(m);
dx.SubmitChanges();

}

return m.ID;
}
catch (Exception ex)
{
// handle this
}
finally
{
if(dx != null)
dx.Dispose();
}

在使用 DataContext 时使用 using 关键字是个好主意

using ( MainsDataContext dx = new MainsDataContext())
{
Main m = dx.Main.SingleOrDefault(s => s.Name == name);

if ( m == null)
{
Guid g = Guid.NewGuid();

m = new Main
{
Name = name,
ID = g
};

dx.Mains.InsertOnSubmit(m);
dx.SubmitChanges();

}

return m.ID;
}

关于c# - 像这样使用嵌套的 Try..Catch block 不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1602102/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com