自從做公司的SNS社區以來,寫了不少的C#代碼,與C++相比,C#是易于使用的,開發效率提高很多倍,其中印象比較深刻的是,在一個C#工程中,可以通過向導添加配置文件,默認文件名為App.Config,是XML格式,一般內容為:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>

<add key="Ip" value="localhost"/>
<add key="Port" value="8888"/>
<add key="ServiceName" value="Indexer"/>


</appSettings>
</configuration>
通過在appSettings里面添加add元素,即可實現通常的配置功能,更重要的是,可以進一步擴展為多級的樹形結構,與Ini格式相比,更直觀,可讀性更強,下面是基于CMarkup(http://www.firstobject.com/)的一個簡單實現:
頭文件如下:
#pragma once

#include <string>
#include <map>


class AppConfig


{
public:
AppConfig(void);
~AppConfig(void);

int GetInt(std::string key);
std::string GetString(std::string key);
private:
std::map<std::string,std::string> config_map_;
};
extern AppConfig appConfig;
源文件如下:

#include "AppConfig.h"
#include "Markup.h"

AppConfig appConfig;


AppConfig::AppConfig(void)


{
CMarkup parser;
if (!parser.Load( "App.Config" ))

{
return;
}
if (parser.FindChildElem("appSettings"))

{
parser.IntoElem();
while (parser.FindChildElem("add"))

{
std::string key = parser.GetChildAttrib("key");
std::string value = parser.GetChildAttrib("value");
config_map_[key] = value;
}
parser.OutOfElem();
}
}

AppConfig::~AppConfig(void)


{
}

int AppConfig::GetInt( std::string key )


{
if (config_map_.find(key) != config_map_.end())

{
return atoi(config_map_[key].c_str());
}
else

{
return 0;
}
}

std::string AppConfig::GetString( std::string key )


{
if (config_map_.find(key) != config_map_.end())

{
return config_map_[key];
}
else

{
return "";
}
}
測試代碼為:
// MarkupTest.cpp : 定義控制臺應用程序的入口點。
//

#include "stdafx.h"

#include "AppConfig.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
cout << appConfig.GetString("Ip") << "-----" << appConfig.GetInt("Port") << "----" << appConfig.GetString("ServiceName") << endl;
return 0;
}















頭文件如下:


































































































測試代碼為:

















