简体   繁体   中英

Is it possible to create extension Fields in c#?

I need to add some information to a class of type DataRecord

I would like to embed in every instance inheriting from IDataRecord a Dictionary

Is it possible to achieve this using Extension Fields? (something like Extension Method)

No, there is no such feature in C#.

It wouldn't really make sense to add it either, as there wouldn't be a well defined location to store the data for that field. Dynamically increasing the size of an existing object isn't really feasible, given the design of the language. It's important that the size of all object instances is constant.

No, this is not possible. Extension methods are nothing more than static methods which are passed the object as this reference.

Alternatives:

  • Extension method which uses some sort of static Dictionary
  • Maybe use mixin libraries (eg re-mix of http://www.re-motion.org )
  • Use a common base class?
  • Use a wrapper, eg ClassWithDictionary<MyClassA> which kind of decorates the original object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM