goto语句会引起程序混乱?使用goto解决实际问题

总看到书上说goto语句会引起程序的混乱,我想引起混乱是针对于编程新手不懂得如何使用而言,

既然设计出了goto那自然有它存在的道理,我们通过如下的例子来说明goto的使用

 

例子采自我的项目OPS.CSite中的读取配置的代码

namespace OPS.CSite
{
    using System;
    using System.Resources;
    using System.IO;
    using System.Web;
    using System.Xml;

    internal class Config
    {
        private static Site site;

        private static readonly string _configFile;

        static Config()
        {
            _configFile = AppDomain.CurrentDomain.BaseDirectory + "config.xml";
            OutputConfigFile();
        }
        private static void OutputConfigFile()
        {
            //将配置文件保存到应用程序根目录下
            FileInfo file = new FileInfo(_configFile);
            if (!file.Exists)
            {
                string config = new ResourceManager(typeof(Properties.Resources)).GetObject("config").ToString();
                using (FileStream fs = new FileStream(file.FullName, FileMode.Create, FileAccess.ReadWrite))
                {
                    StreamWriter sr = new StreamWriter(fs);
                    sr.Write(config);
                    sr.Dispose();
                    fs.Dispose();
                }
            }
        }
        public static Site GetSiteObject()
        {
            object obj = HttpRuntime.Cache["cfg_site"];
            if (obj == null || site == null)
            {
               Load:
            try
                {
                    site = new Site();
                    XmlDocument xd = new XmlDocument();
                    xd.Load(_configFile);
                    site.Name = xd.SelectSingleNode("/config/site/name").Attributes["value"].Value;
                    site.ShortName = xd.SelectSingleNode("/config/site/shortName").Attributes["value"].Value;
                    site.Title = xd.SelectSingleNode("/config/site/title").Attributes["value"].Value;
                    site.Slogan = xd.SelectSingleNode("/config/site/slogan").InnerText;
                    site.Notice = xd.SelectSingleNode("/config/site/notice").InnerText;
                    HttpRuntime.Cache.Insert("cfg_site", "1", new System.Web.Caching.CacheDependency(_configFile));
                }
                catch
                {
                    OutputConfigFile(); goto Load;                }
            }
            return site;
        }

 认真的朋友已经看出来了,当我们在读取XML配置过程中因为某些原因导致异常,如文件不存在了,

 这时候我们仅仅输出一个配置文件是不够的,因为GetSiteObject()还需要返回一个Site对象

 goto在这里的用法为:如果文件不存在则输出一个文件再去读取配置

这样就保证了程序的正常运行,有书上说:

Label:这种语法不要用,试想一下,在我们讨论的环境中还可以使用while循环来达到目的,但很明显的

goto更简洁,更合适!

 

转载于:https://www.cnblogs.com/newmin/archive/2011/01/09/csharp-goto.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值