C# 在using语句中返回
我有下面的函数,它接受一个雇员id,并在雇员处于活动状态时返回C# 在using语句中返回,c#,entity-framework,C#,Entity Framework,我有下面的函数,它接受一个雇员id,并在雇员处于活动状态时返回 public employee GetEmployee(int empId) { using(var dbcontext = new dbentities()) { return dbcontext.employee.Where(emp => emp.id == empId and emp.IsActive == true); } } 问题:我使用了一个using语句,因此每当using块结束时,usi
public employee GetEmployee(int empId)
{
using(var dbcontext = new dbentities())
{
return dbcontext.employee.Where(emp => emp.id == empId and emp.IsActive == true);
}
}
问题:我使用了一个
using
语句,因此每当using块结束时,using语句中创建的对象都将被释放。不过,在这里,我已经在实际使用块结束之前编写了return语句,那么我的对象是否将被释放?我的方法正确吗?dispose是如何发生的?using语句的实际行为类似于Try/Finally,如下所示:
try
{
var dbcontext = new dbentities()
return dbcontext.employee.where(emp => emp.id == empId and emp.IsActive == true);
}
finally
{
if(dbcontext != null)
((IDisposable)dbcontext).Dispose(); //Per the comment below
}
无论发生什么情况,
最终
块始终被执行,因此上下文将始终被释放。唯一被释放的东西是使用块在中明确声明的东西,即分配给dbcontext
的东西。实际的employee对象未被处置,并且是完全可用的-但是,由于数据上下文不可用,任何诸如延迟加载或对象导航之类的功能都将拒绝工作
顺便说一句-它可能应该是Single
或SingleOrDefault
:
return dbcontext.employee.Single(
emp => emp.id == empId and emp.IsActive == true);
从技术上讲,在IL级别,您不能在一个try块中执行ret
(这适用于所有代码,而不仅仅是使用
),因此它实际上是像编写代码一样实现的:
public employee GetEmployee(int empId)
{
employee <>tmp;
dbentities dbcontext = new dbentities();
try {
<>tmp = dbcontext.employee.Single(
emp => emp.id == empId and emp.IsActive == true);
} finally {
if(dbcontext != null) ((IDisposable)dbcontext).Dispose();
// note that for classes this cast is a no-op and doesn't need any IL;
// the above gets a little more complex for structs - using
// constrained call and no null-check
}
return <>tmp;
}
public employee GetEmployee(int-empId)
{
员工tmp;
dbentities dbcontext=新的dbentities();
试一试{
tmp=dbcontext.employee.Single(
emp=>emp.id==empId和emp.IsActive==true);
}最后{
如果(dbcontext!=null)((IDisposable)dbcontext.Dispose();
//注意,对于类来说,这个cast是无操作的,不需要任何IL;
//对于使用structs的用户来说,上面的内容稍微复杂一些
//约束调用和无空检查
}
返回tmp;
}
Its最后再试一次
,没问题。你们都说得对,我今天早上需要更多的咖啡。根据您的评论进行更新。这几乎是正确的。为什么不完全正确呢?请参阅和,
不是C#关键字。