多年来,我一直在努力解决这个问题,通常只是以自己的方式编写代码,但现在是时候解决它了。
我声明了一个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’
发布于 2019-07-11 19:34:56
匿名类型是语法糖,以避免您命名它们。编译器使用匿名类型来让您专注于程序想要做的事情。
由于这个原因,如果你最终引用了一个匿名类型,这意味着它不再是匿名的:)只要给它一个名字,你的问题就会消失:
MyType 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 MyType
{
s,
r
}).Single();
}
catch (Exception)
{
// here dt_stop can be used
throw;
}MyType可以是System.Tuple或标准类。为了保留您的语义,您可以将其设置为DTO (填写您的类型,因为我无法从您的源中推断出它们):
internal sealed class MyType
{
public <The type of s> S {get; set;}
public <The type of r> R {get; set;}
}发布于 2019-07-11 19:36:06
您可以声明匿名类型的默认实例,如下所示:
var temp = new {A = default(int), B = default(int)};
try
{
temp = new {A= 1, B=2};
}
catch (Exception)
{
}发布于 2019-07-11 19:34:00
您是否尝试过在外部声明expando对象?
dynamic dt_stop = new ExpandoObject();它是一个在运行时工作的动态对象
https://stackoverflow.com/questions/56988138
复制相似问题