Is it possible to create variable in parent class, that would initialized once per derrived type?

心已入冬 提交于 2020-01-24 19:53:10

问题


I'm using IDataErrorInfo interface to validate my entities. As long as validation logic is reading metadata from attributes, it is the same for all entities, so I've created class

public class DataErrorInfo : IDataErrorInfo

And all entities are derriving from it. Thing is, that I wish to cache reflection info for derived classes to speed up validation, so every entity type should initialize this cache once per running application.

I was thinking to use static readonly field, but found out, that it is initialized with first used entity type's reflection info, so if there's entity A and entity B, and entity A is accessed first, entity B will have entity A reflection cache.


回答1:


In a generic class if you have a static it's for the closed generic type you can leverage this. Define your base class as a generic (with a somewhat odd looking but valid constraint)

public class DataErrorInfo<T> : IDataErrorInfo where T : DataErrorInfo<T>{
...
}

you then define your derived class like this (notice that the derived class itself is passed as T to the base generic type)

public class EntityClass : DataErrorInfo<EntityClass>{
...
}

that way any static is scoped to the derived class not the parent class as long as you don't do as below

public class AnotherEntityClass : DataErrorInfo<EntityClass>{
...
}



回答2:


You could use a Dictionary<Type, DataErrorInfo> implemented as a Singleton.

The Singleton pattern enforces that only one Dictionary exists in memory. The Dictionary itself will enforce the constraint that each type gets one entry as a Key. Your Value is going to be whatever reflection info you want cached. In this case it looks like that's DataErrorInfo.



来源:https://stackoverflow.com/questions/11260209/is-it-possible-to-create-variable-in-parent-class-that-would-initialized-once-p

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!