是否可能在父类中创建变量,每个派生类型会初始化一次? [英] Is it possible to create variable in parent class, that would initialized once per derrived type?

查看:106
本文介绍了是否可能在父类中创建变量,每个派生类型会初始化一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用IDataErrorInfo接口来验证我的实体。只要验证逻辑从属性读取元数据,所有实体都是一样的,所以我创建了类

  public class DataErrorInfo:IDataErrorInfo 

并且所有实体都从中获取。事情是,我希望缓存派生类的反射信息,以加快验证,因此每个实体类型应该初始化这个缓存一次每个运行的应用程序。



我想使用 static readonly 字段,但发现它是用第一次使用的实体类型的反射信息初始化的,因此如果有实体A和实体B,实体B将具有实体A反射缓存。

解决方案

在泛型类中,如果你有一个静态的,可以利用这个。
将你的基类定义为一个泛型(有一些看起来有点但有效的约束)

  public class DataErrorInfo< T> ; :IDataErrorInfo其中T:DataErrorInfo <$> 
>然后定义你的派生类像这样(注意派生类本身作为T传递给基本通用类型)

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

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


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.

解决方案

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>{
...
}

这篇关于是否可能在父类中创建变量,每个派生类型会初始化一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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