0

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

然后按照文档设置一对类(并在 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 之后,它仍然为空:

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# 问题的副本,其答案是一本非常不具体的信息。这是一个特殊而精确的案例,涉及一个特定的框架,该框架本身就有问题。


4

1 回答 1

1

忘记了配置属性。我猜这些对于 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;
        }
    }
}
于 2017-08-24T20:42:56.110 回答