使用静态泛型类? [英] Uses for static generic classes?
问题描述
什么是一个的静态泛型类在C#中的主要用途?何时应该使用吗?什么例子最能说明其使用情况如何?
What are the key uses of a Static Generic Class in C#? When should they be used? What examples best illustrate their usage?
例如。
public static class Example<T>
{
public static ...
}
既然你不能定义在其中扩展方法,他们似乎在他们的效用会有所限制。在话题的Web引用是稀缺的这么清楚有没有使用它们的人很多。这里有一对夫妇: -
Since you can't define extension methods in them they appear to be somewhat limited in their utility. Web references on the topic are scarce so clearly there aren't a lot of people using them. Here's a couple:-
的 http://ayende.com/Blog/archive/2005/10/05/StaticGenericClass.aspx
答案摘要鉴于
的主要问题似乎是什么是的静态泛型类的区别用静态方法的和的非通用静态静态通用成员的课吗?
The key issues appear to be "What's the difference between a static generic class with static methods and a non-generic static class with static generic members?"
的决定要使用哪种出现围绕着是否类需要存储在内部特定类型的状态?
The decision as to which to use appears to revolve around "Does the class need to store type-specific state internally?"
如果没有必要对特定类型的内部存储然后静态非通用类与一般的静态方法似乎是可取的,因为调用的语法是更好,你可以在其中定义扩展方法。
If there is no need for type-specific internal storage then a static non-generic class with generic static methods appears to be preferable because the calling syntax is nicer and you can define extension methods within it.
推荐答案
我用静态泛型类的缓存反射重码。
I use static generic classes for caching reflection-heavy code.
比方说,我需要建立一个表达式树实例化对象。我在类的静态构造函数,一旦建立,它编译成一个lambda表达式,然后缓存它在静态类的成员。我常常不使这些类公开评税 - 他们通常是其他类帮手。通过这种方式缓存我的表情,我避免需要缓存在某种词典<我的表情;类型,委托方式>
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<Type, delegate>
.
有在 BCL 的这种模式的一个例子。的(的DataRow
)扩展方法字段< T>()
和 SetField< T>( )
使用(私人)静态泛型类 System.Data.DataRowExtensions + UnboxT< T>
。检查它与反射器。
There is an example of this pattern in the BCL. The (DataRow
) extension methods Field<T>()
and SetField<T>()
use the (private) static generic class System.Data.DataRowExtensions+UnboxT<T>
. Check it out with Reflector.
这篇关于使用静态泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!