链接app.config中的自定义配置节
本文关键字:自定义 配置 app config 链接 | 更新日期: 2023-09-27 18:06:04
我的app.config
有这些自定义部分:
<Animals>
<add Type="Elephant" Name="Dumbo" Age="22" />
<add Type="Giraffe" Name="Shorty" Age="5" />
<add Type="Giraffe" Name="Mike" Age="7" />
<add Type="Lion" Name="Shaggy" Age="2" />
</Animals>
<Zoos>
<add Name="New York Zoo" Animals="Dumbo,Shorty" />
<add Name="Paris Zoo" Animals="Mike,Shaggy" />
</Zoos>
我有这些标准类:Animal
, AnimalCollection
, Zoo
, ZooCollection
。
Zoo
完全符合预期,看起来像这样:
public class Zoo : ConfigurationElement {
[ConfigurationProperty("Name", IsRequired=true)]
public string Name { get { return base["Name"] as string; } }
// I don't want this:
[ConfigurationProperty("Animals", IsRequired=true)]
public string Animals { get { return base["Animals"] as string; } }
// I want something like this:
/*
[ConfigurationProperty("Animals", IsRequired=true)]
public IEnumerable<Animal> Animals { get { return ...?
*/
}
所以Zoo.Animals
是Animal
实例名称的CSV字符串。但是我想要的是一个IEnumerable<Animal>
属性。
我该怎么做?
基本上,您需要提供一种将逗号分隔的字符串值转换为IEnumerable的方法。这可以通过提供一个定制的TypeConverter来实现。所以你的Zoo类应该是这样的:
public class Zoo : ConfigurationElement
{
[ConfigurationProperty("Name")]
public string Name
{
get { return (string)base["Name"]; }
}
[TypeConverter(typeof(AnimalConverter))]
[ConfigurationProperty("Animals")]
public IEnumerable<Animal> Animals
{
get { return (IEnumerable<Animal>)base["Animals"]; }
}
}
和AnimalConverter是:
public class AnimalConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
AnimalCollection animals = AnimalSettings.Settings.AnimalList;
List<Animal> result = new List<Animal>();
foreach (string animalName in value.ToString().Split(','))
{
foreach (Animal animal in animals)
{
if (animalName == animal.Name)
{
result.Add(animal);
}
}
}
return result;
}
}
当我用一个控制台应用程序测试它时:
class Program
{
static void Main(string[] args)
{
AnimalCollection animals = AnimalSettings.Settings.AnimalList;
foreach (Animal animal in animals)
{
Console.WriteLine($"{animal.Name}'t't{animal.Age}'t't{animal.Type}");
}
Console.WriteLine();
ZooCollection zoos = ZooSettings.Settings.ZooList;
foreach (Zoo zoo in zoos)
{
Console.WriteLine(zoo.Name);
foreach (Animal animal in zoo.Animals)
{
Console.WriteLine($"{animal.Name}'t't{animal.Age}'t't{animal.Type}" );
}
Console.WriteLine();
}
}
}
我得到了这些结果:
Dumbo 22 Elephant
Shorty 5 Giraffe
Mike 7 Giraffe
Shaggy 2 Lion
New York Zoo
Dumbo 22 Elephant
Shorty 5 Giraffe
Paris Zoo
Mike 7 Giraffe
Shaggy 2 Lion