ConfigurationElementCollection 具有许多不同类型的 ConfigurationElement [英] ConfigurationElementCollection with a number of ConfigurationElements of different type

查看:34
本文介绍了ConfigurationElementCollection 具有许多不同类型的 ConfigurationElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以有一个 CollectionElementCollection,其中包含多个不同类型的 CollectionElements,例如:

Is it possible to have a CollectionElementCollection with a number of different by type CollectionElements, e.g.:

<collection>
    <add type="MyType1, MyLib" Type1SpecificProp="1" />
    <add type="MyType2, MyLib" Type2SpecificProp="2" />
</collection

我拥有此类解决方案所需的所有课程:

I have all classes required for such solution:

class MyCollection : ConfigurationElementCollection { }
class MyElement : ConfigurationElement { }
class MyType1 : MyElement { }
class MyType2 : MyElement { }
...
etc

但是当我启动我的应用程序时,我遇到了下一个可预测的错误:

but when I start my application I'm getting next predictable error:

无法识别的属性Type1SpecificProp".

Unrecognized attribute 'Type1SpecificProp'.

因为 Type1SpecificProp 是在 MyType1 而非 MyElement 中定义的,特别是如果 MyCollection 有下一个方法:

because Type1SpecificProp is defined in MyType1 not MyElement, especially if MyCollection has next method:

protected override ConfigurationElement CreateNewElement()
{
    return new MyElement(); // but I want instantiate not the base class but by a type given
}

即返回基类,因此子类中的 OnDeserializeUnrecognizedAttribute() 永远不会被调用.

i.e. returns base class thus OnDeserializeUnrecognizedAttribute() in child classed are never been called.

那么问题来了:如何让子类自己解析未知元素?

So the question is: how to let child classes to resolve unknown elements by their self?

推荐答案

Microsoft.Practices.EnterpriseLibrary.Common.Configuration.PolymorphicConfigurationElementCollection 做这项工作很有魅力.

Microsoft.Practices.EnterpriseLibrary.Common.Configuration.PolymorphicConfigurationElementCollection<T> from EntLib5 do this job as a charm.

这篇关于ConfigurationElementCollection 具有许多不同类型的 ConfigurationElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆