【发布时间】:2019-07-11 20:35:09
【问题描述】:
多年来我一直在为此苦苦挣扎,通常只是编写代码解决它,但现在是时候解决它了。
我正在声明一个返回新匿名类型的 var,并希望将其放入 try/catch 中。 但是,这样做意味着它超出了范围,以后的代码显然无法看到。 通常我只是先声明它,然后将代码包装在 try/catch 中,然后在其中重新分配,例如:
int result = 0;
try
{
result = 77; //real code goes here
}
catch (Exception)
{
throw;
}
但这是我的真实代码,我无法弄清楚如何做这样的事情:
try
{
var dt_stop = (from s in cDb.DistributionStopInformations
join r in cDb.DistributionRouteHeaders on s.RouteCode equals r.RouteCode
where r.RouteDate == s.RouteDate &&
r.BranchId == s.BranchId &&
(r.CompanyNo == companyNo && s.CompanyNo == companyNo)
&& s.UniqueIdNo == uniqueId
select new
{
s,
r
}).Single();
}
catch (Exception)
{ //no this will not be blank
throw;
}
更新: 在此之后我确实广泛使用 dt_stop,如果分配数据有问题,我想了解一下。
我创建了以下类:
public class StopData
{
public DistributionStopInformation S { get; set; }
public DistributionRouteHeader R { get; set; }
}
然后我尝试使用是这样的:
StopData dt_stop = null;
try
{
dt_stop = (from S in cDb.DistributionStopInformations
join R in cDb.DistributionRouteHeaders on S.RouteCode equals R.RouteCode
where R.RouteDate == S.RouteDate &&
R.BranchId == S.BranchId &&
(R.CompanyNo == companyNo && S.CompanyNo == companyNo)
&& S.UniqueIdNo == uniqueId
select new StopData
{
S,
R
}).Single();
}
catch (Exception)
{
//YES....THERE WILL BE CODE HERE
throw;
}
我得到 无法使用集合初始化程序初始化类型“StopData”,因为它没有实现“System.Collections.IEnumerable”
【问题讨论】:
-
你实际上有一个catch块,除了抛出什么都不做吗?如果是这样,我强烈建议将其完全删除。
-
如果
dt_stop只填充了try/catch内的数据,那以后为什么还要使用呢?你会冒NullReferenceException的风险 -
你可以在尝试之前声明一个动态变量,然后再使用它
-
匿名对象与使用它的代码紧密耦合,因此您可以将该代码放在 try catch 块中。如果世代和用途如此不同以至于它们应该分开,则表明您应该定义一种类型(正如许多答案所暗示的那样)
-
@JonSkeet - 不,它会被填写
标签: c#