首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在try catch c#中使用匿名类型

在try catch c#中使用匿名类型
EN

Stack Overflow用户
提问于 2019-07-11 19:27:17
回答 5查看 349关注 0票数 4

多年来,我一直在努力解决这个问题,通常只是以自己的方式编写代码,但现在是时候解决它了。

我声明了一个var,它返回一个新的无名氏类型,并想把它放在try/catch中。然而,这样做意味着它超出了范围,并且显然不能被后面的代码看到。通常我只需先声明它,然后将代码包装在try/catch中,然后在其中重新赋值,如下所示:

代码语言:javascript
复制
int result = 0;

try
{
    result = 77; //real code goes here
}
catch (Exception)
{
    throw;
}

但这是我的真实代码,我不知道如何做这样的事情:

代码语言:javascript
复制
    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,我想知道分配的数据是否有问题。

我创建了以下类:

代码语言:javascript
复制
 public class StopData
{
    public DistributionStopInformation S { get; set; }

    public DistributionRouteHeader R { get; set; }
}

然后我尝试使用类似于:

代码语言:javascript
复制
 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’

EN

Stack Overflow用户

发布于 2019-07-11 19:45:53

或者使用ValueTuple

代码语言:javascript
复制
var thing = default((int S, int R));
try
{
    thing = /*..*/.Select((s, r));
}
catch (Exception)
{
}
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56988138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档