我在网上找到的 ConfigurationSection
示例 ( for example ) 都有如下代码:
public class ConnectionSection : ConfigurationSection
{
[ConfigurationProperty("Servers")]
public ServerAppearanceCollection ServerElement
{
get { return ((ServerAppearanceCollection)(base["Servers"])); }
set { base["Servers"] = value; }
}
}
为什么它使用方括号从基础访问值“Servers”?是从xml创建这个对象时使用的setter,还是用来覆盖xml文件中的值的setter?如果是,为什么要在此属性上设置属性?
最佳答案
Why is it accessing the value "Servers" from the base using the square brackets?
因为基类 ConfigurationSection 不知道它的继承者要实现什么属性。
所以它公开了a string indexer: this[string]
这使您可以访问从配置中读取的值。
这是一个设计决定。 .NET 团队也可以选择使用反射来获取和设置继承者的属性,但决定不这样做。 (好吧,当然,在配置部分中有很多反射(reflection),但直到 public ServerAppearanceCollection ServerElement { get; set; }
会起作用为止)。
关于c# - 为什么 ConfigurationSection 需要使用字符串查找内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32396189/