【发布时间】:2020-07-19 15:41:20
【问题描述】:
我正在尝试使用配置部分和配置元素。 没有得到价值只得到了钥匙。 我有一个这样的 app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="ProductSettings">
<section name="DellSettings" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<ProductSettings>
<DellSettings>
<add key = "ProductNumber" value="20001" ></add>
<add key =" ProductName" value="Dell Inspiron"></add>
<add key ="Color" value="Black"></add>
<add key =" Warranty" value ="2 Years" ></add>
</DellSettings>
</ProductSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
产品设置类
像这样:
public class ProductSettings : ConfigurationSection
{
[ConfigurationProperty("DellSettings", IsRequired = true)]
public DellFeatures DellFeatures
{
get
{
return (DellFeatures)this["DellSettings"];
}
}
}
DellFeatures 类
像这样解析配置中的每个元素
public class DellFeatures : ConfigurationElement
{
[ConfigurationProperty("ProductNumber", IsRequired = true)]
public int ProductNumber
{
get
{
return (int)this["ProductNumber"];
}
}
[ConfigurationProperty("ProductName", IsRequired = true)]
public string ProductName
{
get { return (string)this[nameof(ProductName)]; }
set { this[nameof(ProductName)] = value; }
}
[ConfigurationProperty("Color", IsRequired = false)]
public string Color
{
get
{
return (string)this["Color"];
}
}
[ConfigurationProperty("Warranty", IsRequired = false)]
public string Warranty
{
get
{
return (string)this["Warranty"];
}
}
}
主类代码如下:
static void Main(string[] args)
{
var productSettings =
ConfigurationManager.GetSection("ProductSettings/DellSettings") as NameValueCollection;
if (productSettings == null)
{
Console.WriteLine("Product Settings are not defined");
}
}
我只能看到键而不是值。我哪里做错了。
【问题讨论】:
标签: c# visual-studio configuration configurationmanager