首页 > 编程语言 >C#程序配置使用示例

C#程序配置使用示例

时间:2023-03-10 14:55:13浏览次数:36  
标签:F1 GetSection return 示例 C# 程序 var MySingleConfig public

通用帮助类

/// <summary>
/// 配置帮助类
/// </summary>
public class ConfigHelper
{
    public static Configuration GetConfig()
    {
        return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    }

    public static T GetSection<T>(string name=null) where T : class
    {
        if(name == null)
        {
            name = typeof(T).Name;
        }
        return GetConfig().GetSection(name) as T;
    }
}

自定义配置AppSettings

  • 配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="F1" value="v1"/>
        <add key="F2" value="v1"/>
        <add key="F3" value="v3"/>
    </appSettings>
</configuration>
  • 代码引用
var appSettings = ConfigurationManager.AppSettings;
var f1 = appSettings.Get("F1");
var f2 = appSettings.Get("F2");
var f3 = appSettings.Get("F3");
Log($"F1:{f1} F2:{f2} F3:{f3}");

自定义配置组(键值对:NameValueSectionHandler)

  • 配置文件
<!--App.config-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <!--自定义键值对配置项-->
        <section name="NameValueNode" type="System.Configuration.NameValueSectionHandler"/>
    </configSections>
    <!--配置内容为指定的外部文件-->
    <NameValueNode configSource="NameValueNode.xml" />
</configuration>

<!--NameValueNode.xml-->
<?xml version="1.0" encoding="utf-8" ?>
<NameValueNode>
    <add key="键值1" value="数值1" />
    <add key="键值2" value="数值2" />
    <add key="键值3" value="数值3" />
</NameValueNode>
  • 代码引用
var nameValueNode = (System.Collections.Specialized.NameValueCollection)ConfigurationManager.GetSection("NameValueNode");
foreach(var v in nameValueNode.AllKeys)
{
    Log($"{v}:{nameValueNode[v]}");
}

自定义配置单项(多属性值:SingleTagSectionHandler)

  • 配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <!--自定义属性配置单项-->
        <section name="SingleTagNode" type="System.Configuration.SingleTagSectionHandler"/>
    </configSections>
    <!--自定义配置详情-->
    <SingleTagNode F1="公平" F2="公正" F3="富强" F4="民主"/>
</configuration>
  • 代码引用
var singleTagNode = (System.Collections.Hashtable)ConfigurationManager.GetSection("SingleTagNode");
foreach (var v in singleTagNode.Keys)
{
    Log($"{v}:{singleTagNode[v]}");
}

自定义对象单项配置

  • 配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <!-- 单节点,name为标签名,type为类型,格式:域名.类名,域名,其中类名的父类为ConfigurationSection -->
        <section name="MySingle" type="AppConfigDemo.MySingleConfig, AppConfigDemo"/>
    </configSections>
    <!--自定义配置详情-->
    <MySingle F1="美利坚" F2="2023" F3="年死掉了"/>
</configuration>
  • 代码实现
namespace AppConfigDemo
{
    public class MySingleConfig : ConfigurationSection
    {
        [ConfigurationProperty("F1")]
        public string F1
        {
            get => (string)this["F1"];
            set => this["F1"] = value;
        }
        [ConfigurationProperty("F2")]
        public int F2
        {
            get => (int)this["F2"];
            set => this["F2"] = value;
        }
        [ConfigurationProperty("F3")]
        public string F3
        {
            get => (string)this["F3"];
            set => this["F3"] = value;
        }

        #region 其他
        public static MySingleConfig Get()
        {
            return ConfigHelper.GetSection<MySingleConfig>("MySingle");
        }
        #endregion
    }
}
  • 配置引用
// 读取配置项到对象
var singleConfig = MySingleConfig.Get();

自定义对象多项(数组或集合)配置

  • 配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <!-- 多节点,name为标签名,type为类型,格式:域名.类名,域名,其中类名的父类为ConfigurationSection -->
        <section name="MyMultiConfig" type="AppConfigDemo.MyMultiConfig, AppConfigDemo"/>
    </configSections>
    <!--自定义配置详情-->
    <MyMultiConfig>
        <Items>
            <add F1="张晓敏" F2="20230310" F3="早上起晚了"/>
            <add F1="何曼丽" F2="20490605" F3="午睡摔倒了"/>
            <add F1="李张绍" F2="30250608" F3="晚上吃多了"/>
        </Items>
    </MyMultiConfig>
</configuration>
  • 代码实现
public class MySingleConfigCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MySingleConfig();
    }

    protected override object GetElementKey(ConfigurationElement e)
    {
        return (e as MySingleConfig).F1;
    }
}


public class MyMultiConfig : ConfigurationSection
{
    [ConfigurationProperty("Items", IsDefaultCollection = false)]
    public MySingleConfigCollection ConfigCollection
    {
        get { return (MySingleConfigCollection)this["Items"]; }
        set { this["Items"] = value; }
    }
}
  • 配置引用
var multiConfig = ConfigHelper.GetSection<MyMultiConfig>();
foreach(MySingleConfig v in multiConfig.ConfigCollection)
{
    
}

标签:F1,GetSection,return,示例,C#,程序,var,MySingleConfig,public
From: https://www.cnblogs.com/arbboter/p/17203343.html

相关文章

  • Spring Bean Scope
    singleton默认情况,为每个SpringIoC容器将单个Bean定义的Scope扩大到单个对象实例。只有一个单例bean的共享实例被管理,所有对具有符合改bean定义的ID的bean的请求都会被s......
  • 使用echarts出现warning:“There is a chart instance already initialized on the dom
    原因:在同一dom容器内,options配置项数据变动,多次渲染导致解决方法:echarts.getInstanceByDom()<divid="echarts"ref="echartsRef"></div<script>letmyChart=......
  • IntelliJ IDEA Community Setup
    卸载旧版本时勾选"Deletecachesandlocalhistory""Deletesettingsandinstalledplugins"以完全删除 自定义安装路径 设置选项:CreateDesktopShortcut在......
  • Python -gdb 查看程序堆栈详情
    MacPython3.7https://www.modb.pro/db/454999安装#搜索仓库$brewsearchgdb#安装$brewinstallgdbError:[email protected]:thebottleneedstheAppleCom......
  • TypeScript学习笔记#1 基础变量
    TypeScript学习笔记#1基础变量1.声明变量,指定变量类型letnum:number;num=10;2.基础类型类型名称写法值string字符串类型letname:string="bob";......
  • 《重构-改善既有代码设计案例》案例之C#版(2)
    书接上文。。。先来看一眼这个AmountFor方法1privateintAmountFor(PerformanceaPerformance,Playplay)2{3intresult;4......
  • 互联网医院开发|线上问诊小程序好处有哪些?
    互联网医院可以通过互联网远程为患者提供常见病、慢性病复诊及健康咨询,并开具处方和配送药物等医疗服务。互联网医院建设分利用线上优势,可以为市民提供便捷的诊疗服务,减少不......
  • Java之BigDecimal 使用总结
     一、BigDecimal 产生   Java在java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算。双精度浮点型变量double可以处理16位有效数,但在实际......
  • C#中连接Oracle数据库
    1、nuget添加 Oracle.ManagedDataAccess  2、连接字符串配置<connectionStrings> <!--连接字符串--> <addname="FeesConn"connectionString="UserId=sa;passwo......
  • Cookie前端优化
    cookie由于http请求每次都是独立的,它的执行情况和结果与前面的请求、之后的请求没有直接关系,没有办法区分当前客户,所以产生了cookie。使特定客户端与服务器产生联系cooki......