Sitefinity config 属性 null,即使在设置后立即

Sitefinity config property null, even immediately after being set

我创建了一个新的配置文件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);

我不知道如何克服这个特殊的异常,其中引用在设置后立即为空。有人看到我遗漏了什么吗?

更新

经过进一步调整,我认为 SpecialConfig.UnicornSettings 上的 getter 或 setter 有问题...不过我不确定那是什么。


免责声明

我了解什么是空引用异常,以及一般来说如何识别和克服空引用异常。这不是某个特定 C# 问题的副本,其答案是非常不具体的 book 信息。这是一个特殊而精确的案例,涉及一个特定的框架,值得自己提出问题。


忘记了 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;
        }
    }
}