我已经创建了一个新的配置文件Special.config
:
<?xml version="1.0" encoding="utf-8"?>
<SpecialConfig xmlns:config="urn:telerik:sitefinity:configuration" xmlns:type="urn:telerik:sitefinity:configuration:type" config:version="10.0.6401.0">
<UnicornSettings HornSize="#{HornSize}" HoofColor="#{HoofColor}" />
</SpecialConfig>
然后followed the documentation设置一对类(并在Global.asax.cs中注册配置)文件:
public class SpecialConfig : ConfigSection
{
public UnicornSettingsElement UnicornSettings
{
get
{
return (UnicornSettingsElement)this["UnicornSettings"];
}
set
{
this["UnicornSettings"] = value;
}
}
}
public class UnicornSettingsElement : ConfigElement
{
public UnicornSettingsElement(ConfigElement parent) : base(parent)
{
}
public String HornSize
{
get
{
return (String)this["HornSize"];
}
set
{
this["HornSize"] = value;
}
}
public String HoofColor
{
get
{
return (String)this["HoofColor"];
}
set
{
this["HoofColor"] = value;
}
}
}
但是即使在显式实例化SpecialConfig.UnicornSettings之后,它仍然是null:
UnicornSettings config = Config.Get<UnicornSettings>();
config.UnicornSettings = new UnicornSettingsElement(config);
config.UnicornSettings.HornSize = HornSize; //<-- config.UnicornSettings is null
config.UnicornSettings.HoofColor = HoofColor;
ConfigManager manager = ConfigManager.GetManager();
manager.SaveSection(config);
我不知道如何克服此特定异常,其中引用在设置后立即为null。有人看到我错过的东西吗?
更新
经过进一步的摆弄,我认为SpecialConfig.UnicornSettings上的getter或setter有问题......我不确定那可能是什么。
声明
我理解空引用异常是什么,并且一般来说如何识别和克服空引用异常。这不是特定C#问题的副本,其答案是非常非特定的书信息。这是一个特殊而精确的案例,涉及一个特定的框架,保证自己的问题。
答案 0 :(得分:1)
忘记ConfigurationProperties。我猜这些对于getter / setter访问属性的方式是必要的:
public class SpecialConfig : ConfigSection
{
[ConfigurationProperty("UnicornSettings")]
public UnicornSettingsElement UnicornSettings
{
get
{
return (UnicornSettingsElement)this["UnicornSettings"];
}
set
{
this["UnicornSettings"] = value;
}
}
}
public class UnicornSettingsElement : ConfigElement
{
public UnicornSettingsElement(ConfigElement parent) : base(parent)
{
}
[ConfigurationProperty("HornSize", IsRequired = true)]
public String HornSize
{
get
{
return (String)this["HornSize"];
}
set
{
this["HornSize"] = value;
}
}
[ConfigurationProperty("HoofColor", IsRequired = true)]
public String HoofColor
{
get
{
return (String)this["HoofColor"];
}
set
{
this["HoofColor"] = value;
}
}
}