总看到书上说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更简洁,更合适!