是否可以拥有一个包含许多不同类型的集合元素的 Collection ElementCollection,例如:
<collection>
<add type="MyType1, MyLib" Type1SpecificProp="1" />
<add type="MyType2, MyLib" Type2SpecificProp="2" />
</collection
我拥有此类解决方案所需的所有课程:
class MyCollection : ConfigurationElementCollection { }
class MyElement : ConfigurationElement { }
class MyType1 : MyElement { }
class MyType2 : MyElement { }
...
etc
但是当我启动我的应用程序时,我遇到了下一个可预测的错误:
无法识别的属性“Type1SpecificProp”。
because Type1SpecificProp
定义于MyType1
not MyElement
,特别是如果MyCollection
有下一个方法:
protected override ConfigurationElement CreateNewElement()
{
return new MyElement(); // but I want instantiate not the base class but by a type given
}
即返回基类OnDeserializeUnrecognizedAttribute()
在儿童班级中从未被叫过。
那么问题来了:如何让子类自己解决未知元素呢?
我也调查了这一点。PolymorphicConfigurationElementCollection<T>
似乎已弃用 http://msdn.microsoft.com/en-us/library/bb750549%28v=pandp.31%29.aspx。
编辑:不是,请参阅下面“abatishchev”的评论,我只是链接旧版本。
Rest Wing 的解决方案很有希望,但不幸的是需要调用驻留在另一个命名空间中的内部方法。虽然这可以通过反射实现,但在这种情况下,它不会因为编码美观而付出代价。
我也用 Reflection 深入研究了源代码,并提出了以下解决方案:
[ConfigurationCollection(typeof(ElementBaseConfig), CollectionType=ConfigurationElementCollectionType.BasicMap)]
public class MyTypesConfigCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
// Not used but function must be defined
return null;
}
protected override object GetElementKey(ConfigurationElement element)
{
return element;
}
protected override ConfigurationElement CreateNewElement(string elementName)
{
switch (elementName)
{
case "mytype1":
return new MyType1Config();
case "mytype2":
return new MyType2Config();
default:
throw new ConfigurationErrorsException(
string.Format("Unrecognized element '{0}'.", elementName));
}
}
protected override bool IsElementName(string elementName)
{
// Required to be true
return true;
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
}
CollectionType 的覆盖是必需的,即使这已通过顶部的属性指定。当不重写基类时,CollectionType 仍然引用“AddRemoveClearMap”,它不会触发所需的“CreateNewElement(string elementName)”函数,但它是无参数变体“CreateNemElement()”。出于同样的原因,覆盖的 IsElementName 函数应该返回 true。
请注意,我创建了一个 ElementBaseConfig,它是 MyType1Config 和 MyType2Config 的基类,您可以在其中定义一些共享属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)