这有点复杂,但我会尽力解释清楚。
我有一个通用代码组件的类库;我尝试做一些常见的ConfigurationHandler
基类,以简化创建自定义配置部分、集合和元素。
我最终得到的是:
The ConfigurationSectionBase
类是通用的,采取TConfElementCollection As {ConfigurationElementCollection, New}
作为类型约束。
This ConfigurationSectionBase
类包含一个Public MustOverride Property Collection As TConfElementCollection
.
这个想法是,在使用类库的项目中,他们只需覆盖集合并用<ConfigurationProperty("CollectionName")>
属性,例如:
<ConfigurationProperty("CollectionName")>
Public Overrides Property Collection As DerivedConfigurationElementCollection
Get
Return TryCast(Me("CollectionName"), DerivedConfigurationElementCollection)
End Get
Set(value As DerivedConfigurationElementCollection)
Me("CollectionName") = value
End Set
End Property
这工作正常 - 在使用应用程序中我可以创建该部分,然后在我的配置处理程序类中我可以调用
Dim section As DerivedSection = (TryCast(Config.GetSection("DerivedSection"), DerivedSection))
Dim coll as DerivedConfigurationElementCollection = section?.Collection
那么,我的下一个想法是为什么不也抽象 Config Handler 类,并将其移至基类中?
事实证明这更复杂,但我最终在一个ConfigurationHandlerBase
DLL 中的类:
Protected Function GetCollection(Of TCollection As ConfigurationElementCollection, TSection As {ConfigurationSectionBase(Of TCollection), New})(sectionName as String) As TCollection
Dim s As TSection = (TryCast(Config.GetSection(sectionName), TSection))
Return s?.Collection ' AccessViolationException is thrown on this line
为了尝试诊断问题,我以与 Collection 相同的方式创建了一个 String 属性(MustOverride
in the ConfigurationSectionBase
DLL 中的类,在使用的应用程序中被覆盖),然后尝试从类库访问它 - 再次出现同样的问题。
所以我认为这个问题与MustOverride
并且 DLL 代码无法识别派生类已覆盖该属性。
如果我返回TSection
相反,从 DLL 方法中访问,然后访问Collection
使用 DLL 的应用程序中的属性;我可以很好地访问收藏集。
奇怪的是,如果我放入断点,Visual Studio 会很高兴地向我显示Collection
属性,不抛出任何异常。
另外,如果我更换(TryCast(Config.GetSection(sectionName), TSection))
with new TSection()
,我仍然收到 AccessViolationException - 所以据我所知,这与我正在访问配置文件的事实无关。
以前有人遇到过这个吗?或者我的下一步可以采取什么措施来解决此异常?