[英]Is there a way to set configuration runtime options in code rather than in the config file?
[英]XML Config, How can I read a configuration file with a list/array of values rather than a single value
如果我有一个配置文件,其中包含以下配置中的值列表。
配置文件是一个 xml 文件...
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<Employees foor="bar">
<Employee name="aaa" surname="bbb"/>
<Employee name="ddd" surname="eee"/>
<Employee name="fff" surname="ggg"/>
</Employees>
</configuration>
使用Microsoft.Extensions.Configuration
,我尝试加载 xml 如下
public class Employee
{
public string Name{get;set;}
public string Surname{get;set;}
}
...
public class Employees
{
public List<Employee> Employees{ get; set;}
public string Foo {get; set; }
}
...
var configurationBuilder = new ConfigurationBuilder()
AddXmlFile(path: "\\MyConfig.config")
.Build();
var employees = configurationBuilder.GetSection("Employees").Get<Employees>()
...
但是返回的列表是 null,如果我将它们上移一级,我可以读取单个值,但我想读取列表中的值列表。
如果我在 class 中有一个 class 它也不起作用
例如
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<Outer foor="bar">
<Inner name="aaa" surname="bbb"/>
</Outer>
</configuration>
场景 1 - 保留Employees
xml 包装元素
为了加载Employee
xml 元素,包装器 class 上的相应属性必须具有相同的名称; 所以将Employees
更改为Employee
。
让我们更正 xml 中的foor
属性,从<Employees foor="bar">
到<Employees foo="bar">
因为Employees
class 具有Foo
属性。
public class Employees
{
public List<Employee> Employee { get; set;}
public string Foo { get; set; }
}
下面显示了检索employees
部分的结果。
var employees = configurationBuilder.GetSection("Employees").Get<Employees>();
如果您不喜欢单一的Employee
属性,那么您可以将其设为private
,但在检索时必须考虑到这一点。
然后,您将public
Employees
定义为“传递”属性。
请注意,由于CS0542
编译错误,您不能拥有Employees
class 和具有相同名称的属性,这将通过将 class 重命名为例如Staff
来解决。
public class Staff
{
private List<Employee> Employee { get; set; }
public List<Employee> Employees => Employee;
public string Foo { get; set; }
}
var employees = configurationBuilder.GetSection("Employees")
.Get<Staff>(o => o.BindNonPublicProperties = true);
场景 2 - 不使用Employees
xml 包装器元素
如下声明 xml。
<configuration>
<Employee name="aaa" surname="bbb" />
<Employee name="ddd" surname="eee" />
<Employee name="fff" surname="ggg" />
</configuration>
检索员工作为Employee
列表。
var employees = configurationBuilder.GetSection("Employee").Get<List<Employee>>();
这是其中一种方式,您可以如图所示进行操作:
<util:list id="myColours" value-type="java.lang.String">
<value>red</value>
<value>green</value>
<value>blue</value>
<value>yellow</value>
<value>brown</value>
<value>orange</value>
</util:list>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.