C#动态属性(.NET Framework4.5支持)

时间:2023-12-11 23:52:26

获取方法:

  /*

使用方法:

  1. 在web.config 的<configSections> 节点中添加
<section name="customConfigs" type="FortuneLab.Core.Configurations.CustomConfigsSection,FortuneLab.Core"/> 2. 在web.config 中添加 如下配置
<customConfigs>
<cfg name="dbCommands" fliePath="ConfigFiles\dbCommands.config"/>
<!--根据需要可以继续添加其他 cfg 配置,如
<cfg name="dbConnections" fliePath="ConfigFiles\dbConnections.config"/>
<cfg name="params" fliePath="ConfigFiles\params.config"/>
-->
</customConfigs>
3. cs中通过 ConfigManager.Configs["dbCommands"] 获取
例如 dbCommands 的配置文件内容如下
<?xml version="1.0" encoding="utf-8"?>
<Container>
<A A1="" A2="">
<A3><![CDATA[ xxxxxx ]]></A3>
<A4>
<Parameters>
<Param name="p1"></Param>
<Param name="p2"></Param>
<Param name="p3"></Param>
</Parameters>
</A4>
</A>
</Container> 取A : ConfigManager.Configs["dbCommands"].A
取A1: ConfigManager.Configs["dbCommands"].A.A1
取A2: ConfigManager.Configs["dbCommands"].A.A2
取A3: ConfigManager.Configs["dbCommands"].A.A3
取A4: ConfigManager.Configs["dbCommands"].A.A4
取Parameters: ConfigManager.Configs["dbCommands"].A.Parameters
取Parameters 第一个: ConfigManager.Configs["dbCommands"].A.Parameters["p1"] 或者 ConfigManager.Configs["dbCommands"].A.Parameters[0] 终极用法: 可以将任意一个节点转换为IDictionary<string, dynamic>, 然后再操作
IDictionary<string, dynamic> dict = ConfigManager.Configs["dbCommands"].A as IDictionary<string, dynamic>;
取A1: dict["A1"]
取A2: dict["A2"]
取A3: dict["A3"]
取A4: dict["A4"] IDictionary<string, dynamic> dict1 = dict["A4"] as IDictionary<string, dynamic>;
取Parameters: dict1["Parameters"] IDictionary<string, dynamic> dict2 = dict1["Parameters"] as IDictionary<string, dynamic>;
取Parameters 第一个: dict2["p1"] 或 dict2[0] 备注:
任何使用都可以使用HasMember("memberName"), 取检查是否有这个成员
如果是集合, 可用使用foreach
有Value属性,可以取到尖括号之间的内容,比如<A>hahah</A> , 可以用A.Value 取到其中的值,所以请避免显示定义Value属性 */ public class ConfigManager
{
#region Create Config private static Dictionary<string, dynamic> CreateCustomConfig()
{
Dictionary<string, dynamic> allConfig = new Dictionary<string, dynamic>();
CustomConfigsSection config = (CustomConfigsSection)ConfigurationManager.GetSection("customConfigs");
for (int i = 0; i < config.CustomConfigs.Count; i++)
{
var perConfig = config.CustomConfigs[i];
allConfig.Add(perConfig.Name, CreateConfigDyObj(perConfig));
}
return allConfig;
}
private static dynamic CreateConfigDyObj(CustomConfigElement config)
{
string path = HttpContext.Current.Server.MapPath("~/") + config.ConfigFliePath;
XElement doc = XElement.Load(path);
dynamic dyObj = CreateDyObj(doc);
return dyObj;
} private static dynamic CreateDyObj(XElement elem)
{
dynamic dyObj = new ExpandoObject();
var dict = (IDictionary<string, dynamic>)dyObj; #region Elements of elem
/*
* 先检查是否有同名元素,
* 如果有,则新建为XXX = new Dictionary<string,ExpandoObject>();
* 如果没有,则新建为XXX = new ExpandoObject();
*
*/ if (elem.HasElements)
{
var distinctNames = elem.Elements().Select(p => p.Name.ToString()).Distinct();
if (distinctNames.Count() == elem.Elements().Count() && elem.Elements().Count() == 1) //只有一个子元素
{
var cfg_IsList = elem.Attribute("cfg_IsList");
if (cfg_IsList != null && Convert.ToBoolean(cfg_IsList.Value)) //子元素按集合处理
{
WrapDictionary wrapDict = new WrapDictionary();
wrapDict.Add(elem.Elements().First().Attribute("name").Value, CreateDyObj(elem.Elements().First()));
dyObj = wrapDict;
}
else
{
dynamic oo = CreateDyObj(elem.Elements().First());
dict.Add(elem.Elements().First().Name.ToString(), oo);
}
}
else if (distinctNames.Count() == 1) //多个子元素,并且所有子元素都是 相同结构的
{
if (dict.Keys.Count <= 0)
{
WrapDictionary wrapDict = new WrapDictionary();
foreach (var perElem in elem.Elements())
{
wrapDict.Add(perElem.Attribute("name").Value, CreateDyObj(perElem));
} dyObj = wrapDict;
}
}
else if (distinctNames.Count() == elem.Elements().Count()) //多个子元素,所有子元素都是 不同结构的
{
foreach (var perElem in elem.Elements())
{
dynamic oo = CreateDyObj(perElem); dict.Add(perElem.Name.ToString(), oo);
}
}
else
{
throw new Exception(string.Format("{0} subelement set error!", elem.Name.ToString()));
}
}
#endregion #region Nodes of elem
if (!elem.HasElements)
{
if (elem.Nodes().Count() > 0)
{
XNode node = elem.Nodes().FirstOrDefault(p => p.NodeType != System.Xml.XmlNodeType.Comment);
if (node != null && (node.NodeType == System.Xml.XmlNodeType.CDATA || node.NodeType == System.Xml.XmlNodeType.Text))
{
dict.Add("Value", elem.Value);
}
else
{
dict.Add("Value", null);
}
}
else
{
dict.Add("Value", null);
} #region Attributes of elem
if (elem.HasAttributes)
{
foreach (var perAttr in elem.Attributes())
{
if (!dict.ContainsKey(perAttr.Name.ToString()))
dict.Add(perAttr.Name.ToString(), perAttr.Value);
}
}
#endregion
}
#endregion dict.Add("HasMember", new Func<string, bool>(memberName => dict.Keys.Contains(memberName))); return dyObj;
} #endregion private static Dictionary<string, dynamic> _allConfig = null;
public static Dictionary<string, dynamic> Configs
{
get
{
if (_allConfig == null)
{
_allConfig = ConfigManager.CreateCustomConfig();
}
return new Dictionary<string, dynamic>(_allConfig);
}
}
} public class WrapDictionary : IEnumerable
{
Dictionary<string, dynamic> dySet = new Dictionary<string, dynamic>(); public void Add(string memberName, dynamic obj)
{
dySet.Add(memberName, obj);
}
public bool HasMember(string memberName)
{
return dySet.ContainsKey(memberName);
} public dynamic this[string name]
{
get
{
return dySet[name];
}
} public IEnumerator GetEnumerator()
{
foreach (var item in dySet)
{
yield return item.Value;
}
}
}

 ABP CustomConfig

  

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Abp.Configurations
{
public class CustomConfigsSection : ConfigurationSection
{
[ConfigurationProperty("", IsDefaultCollection = true)]
public CustomConfigElementCollection CustomConfigs
{
get
{
return (CustomConfigElementCollection)this[""];
}
} } public class CustomConfigElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new CustomConfigElement();
} protected override object GetElementKey(ConfigurationElement element)
{
return ((CustomConfigElement)element).Name;
} public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
} protected override string ElementName
{
get
{
return "cfg";
}
}
public CustomConfigElement this[int index]
{
get
{
return (CustomConfigElement)BaseGet(index);
}
}
} public class CustomConfigElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
} [ConfigurationProperty("fliePath", IsRequired = true)]
public string ConfigFliePath
{
get { return (string)this["fliePath"]; }
set { this["fliePath"] = value; }
}
}
}

WebConfig配置:

  

 <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="customConfigs" type="Abp.Configurations.CustomConfigsSection,FortuneLab.Abp" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<customConfigs>
<cfg name="FordParames" fliePath="ConfigFiles\Ford\Parames.config" />
<cfg name="LandRoverDBCommands" fliePath="ConfigFiles\LandRover\dbCommands.config" />
<cfg name="PaymentDBCommands" fliePath="ConfigFiles\LandRover\PaymentDBCommands.config" />
<cfg name="LockCarDBCommands" fliePath="ConfigFiles\LandRover\LockCarDBCommands.config" />
<cfg name="InvoiceDBCommands" fliePath="ConfigFiles\LandRover\InvoiceDBCommands.config" />
<cfg name="LRVerifyConfigs" fliePath="ConfigFiles\LandRover\VerifyConfigs.config" />
<cfg name="FordDBCommands" fliePath="ConfigFiles\Ford\dbCommands.config" />
<cfg name="ResourceParames" fliePath="ConfigFiles\Ford\Parames.config" /> </customConfigs>

 使用方法:

  

 private static string ResourcePath = ConfigManager.Configs["ResourceParames"].ResourcePath.Value;