目前,在正確設置它的過程中遇到了一些問題。我在網上做了大量的閱讀,並嘗試了不同代碼的多種配置,但對於下面的自定義xml標籤,我似乎無法使其正常工作。有人可以提供一些關於如何解決這個問題的反饋嗎?我想從其他類訪問這個外部,並遍歷每個「trackInfo」標籤尋找一個特定的關鍵。最後一段代碼是我試圖提取元素並將它們保存爲變量的地方使用自定義xml標籤設置App.Config
我在尋找的事物: - 我在想什麼? - 我如何進入外部課堂?
App.config中:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="trackLog" type="Tracking.TrackConfigSection, Tracking" />
</configSections>
<trackLog>
<trackInfo key="DEV1" env="dev1" url="http://dev1.com" />
<trackInfo key="DEV2" env="dev2" url="http://dev2.com" />
</trackLog>
</configuration>
TrackConfigSection.cs
public class TrackConfigSection : ConfigurationSection
{
private const string SectionName = "trackLog";
public TrackConfigSection()
{
base[""] = new TrackConfigCollection();
}
[ConfigurationProperty("", IsRequired = true, IsKey = false, IsDefaultCollection = true)]
public TrackConfigCollection TrackConfigs
{
get { return ((TrackConfigCollection)(base[""])); }
set { base[""] = value; }
}
public static TrackConfigCollection GetTrackConfigs()
{
return ((TrackConfigSection)ConfigurationManager.GetSection(SectionName)).TrackConfigs;
}
}
TrackConfigCollection.cs
[ConfigurationCollection(typeof(TrackConfigEntry), CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class TrackConfigCollection : ConfigurationElementCollection
{
const string ItemName = "trackInfo";
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((TrackConfigEntry)element).Key;
}
protected override ConfigurationElement CreateNewElement()
{
return new TrackConfigEntry();
}
public new TrackConfigEntry this[string key]
{
get
{
return (TrackConfigEntry)BaseGet(key);
}
}
public bool Contains(string role)
{
return BaseGetAllKeys().Contains(role);
}
}
TrackConfigEntry.cs
public class TrackConfigEntry : ConfigurationElement
{
[ConfigurationProperty("key", IsRequired = true)]
public string Key
{
get { return (string)base["key"]; }
}
[ConfigurationProperty("env", IsRequired = true)]
public string env
{
get { return (string)base["env"]; }
}
[ConfigurationProperty("url", IsRequired = true)]
public string url
{
get { return (string)base["url"]; }
}
}
從其他類
var envName = System.Configuration.ConfigurationManager.AppSettings["env"];
// the envName is in the tags in the app.config
if (TrackConfigSection.GetTrackConfigs().Contains(envStringName))
{
string temp1 = TrackConfigSection.GetTrackConfig("key").ToString(); // variable to get key
string temp2 = TrackConfigSection.GetTrackConfig("env").ToString(); // variable to get env
string temp3 = TrackConfigSection.GetTrackConfig("url").ToString(); // variable to get url
}
是正確的類型?這似乎不是一個正確的程序集/類型名稱模式。 –
您是指「<部分名稱...」? – Masterminder
是的............ –