Uses for static generic classes?

前端 未结 9 1721
猫巷女王i
猫巷女王i 2020-12-08 10:11

What are the key uses of a Static Generic Class in C#? When should they be used? What examples best illustrate their usage?

e.g.

         


        
9条回答
  •  离开以前
    2020-12-08 10:56

    I use static generic classes for caching reflection-heavy code.

    Let's say I need to build an expression tree that instantiates objects. I build it once in the static constructor of the class, compile it to a lambda expression, then cache it in a member of the static class. I often don't make these classes publicly assessable - they are usually helpers for other classes. By caching my expressions in this way, I avoid the need to cache my expressions in some sort of Dictionary.

    There is an example of this pattern in the BCL. The (DataRow) extension methods Field() and SetField() use the (private) static generic class System.Data.DataRowExtensions+UnboxT. Check it out with Reflector.

提交回复
热议问题