Linking custom config sections in an app.config
我的
1 2 3 4 5 6 7 8 9 10 11 12 | <Animals> </Animals> <Zoos> </Zoos> |
我有这些标准分类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 ...? */ } |
因此,
我该怎么做?
基本上,您需要提供一种将逗号分隔的字符串值转换为IEnumerable的方法。这可以通过提供自定义的类型转换器来实现。所以你的动物园课程应该是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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"]; } } } |
动画转换器是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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; } } |
当我用控制台应用程序测试它时:
2我得到了这些结果:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
我希望这有帮助。