Try-Catch和“继续”-这可能吗?我有一部分代码可以查询网络上的所有SQLServer数据库。我首先尝试使用SQL登录访问SQLServer实例,但如果失败,那么我想尝试使用我的Windows凭据进行连接。之后,如果我仍然无法连接,那么我希望代码失败,然后通知用户。所以我想我要问的是如何从Try-Catch块内部循环回到Try-Catch块上方的行:StringconxString=@"DataSource=SQLInstance1;UserID=FOO;Password=BAR;";boolsecondTime=false;使用(SqlConnectionsqlConx=newSqlConnection(conxString)){Try{sqlConx.Open();DataTabletblDatabases=sqlConx.GetSchema("数据库");sqlConx.Close();secondTime=false;Console.WriteLine("找到SQLServer!");}Catch(System.Data.SqlClient.SqlExceptione){如果(!secondTime){secondTime=true;conxString=@"DataSource=SQLInstance1;IntegratedSecurity=True;";//循环回到using语句以再次尝试使用WindowsCreds{else{Console.WriteLine("SQLServernotfoundorcredentialsrefused");}//报告连接用户失败}finally{//重置变量secondTime=false;我可能会走这条路:StringconxString=@"DataSource=Instance1;UserID=FOO;Password=BAR;";//在你的主函数中if(!TryConnect(conxString)){Console.WriteLine("SQLCreditialsfailed.Tryingwithwindowscredentials...");conxString="newconnstring";TryConnect(conxString);}.........//主函数之外的新函数privateboolTryConnect(stringconnString){using(SqlConnectionsqlConx=newSqlConnection(conxString)){Try{sqlConx.Open();DataTabletblDatabases=sqlConx.GetSchema("Databases");sqlConx.Close();}Catch(System.Data.SqlClient.SqlExceptione){返回false;}returntrue;}}成功后可以用for循环结合break:for(intattempt=1;attempt也可以记录是否成功等,或者增加尝试次数或者使次数尝试次数可配置这篇博文(虽然是从2005年开始的)显示了您的问题的可能解决方案:以上是C#学习教程:Try-Catch和“继续”-这可能吗?如果分享的内容对你有用,需要了解更多C#学习教程,希望大家多多关注---使用GotoTryLabel:try{downloadMgr.DownLoadFile("file:///server/file","c:\文件");Console.WriteLine("文件下载成功");}catch(NetworkExceptionex){if(ex.OkToRetry)gotoTryLabel;}写一个包装器publicstaticboolWrapper(DownloadManagerdownloadMgr){try{downloadMgr.DownLoadFile("file:///server/file","c:\file");返回真;}catch(NetworkExceptionex){Console.WriteLine("下载文件失败:{0}",ex.Message);返回(!ex.OkToRetry);}}staticvoidMain(string[]args){while(!Wrapper(downloadMgr));}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
