使用<appSettings>元素定义配置参数
2012-05-22 11:25
549 查看
可以使用应用程序配置文件中的<appSettings>元素保存专门用于应用程序的配置值。例如:
假设Myapp应用程序有一个名为MyInt参数:
<?xml version="1.0" encoding="utf-8" ?>
<configuration
xmls=http://schemas.microsoft.com/.netConfiguration/v2.0>
<appSettings>
<add key="MyInt" value="1234"/>
</appSettings>
</configuration>
下面是MyApp应用程序的代码。在每次执行的时候,代码都会取出MyInt参数的值再乘以10,然后保存新值。
Myapp。cs
using System.Configuration;
class Program{
static void main()
{
Configuration appCfg=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLeverl.None);
AppSettingsSection appSettings=appCfg.AppSettings;
int myInt;
if(int.TryParse(appSettings.Settings["MyInt"].Value, out myInt))
{
System.Console.WriteLine(myInt);
myInt*=10;
appSettings.Settings["MyInt"].value=myInt.ToString();
appCfg.Save();
}
}
}
这个方法存在的缺点:
(1)。 参数值没有类型。我们需要显示地将一个字符串解析为一个整型变量,以获取MyInt的值
(2)。 由于参数的名字是一个字符串,因此无法被编译器验证。这样会降低开发效率,因为开发者无法从智能感知中获益。
假设Myapp应用程序有一个名为MyInt参数:
<?xml version="1.0" encoding="utf-8" ?>
<configuration
xmls=http://schemas.microsoft.com/.netConfiguration/v2.0>
<appSettings>
<add key="MyInt" value="1234"/>
</appSettings>
</configuration>
下面是MyApp应用程序的代码。在每次执行的时候,代码都会取出MyInt参数的值再乘以10,然后保存新值。
Myapp。cs
using System.Configuration;
class Program{
static void main()
{
Configuration appCfg=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLeverl.None);
AppSettingsSection appSettings=appCfg.AppSettings;
int myInt;
if(int.TryParse(appSettings.Settings["MyInt"].Value, out myInt))
{
System.Console.WriteLine(myInt);
myInt*=10;
appSettings.Settings["MyInt"].value=myInt.ToString();
appCfg.Save();
}
}
}
这个方法存在的缺点:
(1)。 参数值没有类型。我们需要显示地将一个字符串解析为一个整型变量,以获取MyInt的值
(2)。 由于参数的名字是一个字符串,因此无法被编译器验证。这样会降低开发效率,因为开发者无法从智能感知中获益。
相关文章推荐
- 使用<appSettings>元素定义配置参数
- <bean>定义中元素ref 和depends-on 的区别
- asp.net读取Web.config的<appSettings></appSettings>
- <connectionStrings>和<appSettings>这个的区别
- System.ArgumentException: 回发或回调参数无效。在配置中使用 < pages enableEventValidation="true"/> 或在页面中使用 <% @ Page
- <activity>元素的android:launchMod属性的使用
- 使用<selector>风格化Android的GridView元素背景
- Android中常常使用shape来定义控件的一些显示属性,今天看了一些shape的使用,对shape有了大体的了解,稍作总结: 先看下面的代码: <shape>
- < jsp:setProperty>元素使用全解
- <一>Ioc控制反转——手把手教学:如何配置并使用单元测试一个spring框架(附源码)
- JSP中使用哪个标签允许向<include/>标签传递参数
- System.ArgumentException: 回发或回调参数无效。在配置中使用 < pages enableEventValidation="true"/>
- HTML5的<meta> 元素移动端的使用技巧
- Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下
- <转>云主机配置OpenStack使用spice的方法
- 回发或回调参数无效。在配置中使用 <pages enableEventValidation="true"/> 或在页面中使用 <%@ Page EnableEventValidation="true"
- 如何在前台使用<%#eval( )%> 传递多个参数
- 回发或回调参数无效。在配置中使用 <pages enableEventValidation="true"/>
- 使用<selector>风格化Android的GridView元素背景
- 回发或回调参数无效。在配置中使用 <pages enableEventValidation="true"/> 或在页面中使用 <%@ Page EnableEventValidation="true"