用于静态泛型类? [英] Uses for static generic classes?
问题描述
C# 中静态泛型类的主要用途是什么?什么时候应该使用它们?哪些例子最能说明它们的用法?
例如
公共静态类示例{公共静态...}
由于您无法在其中定义扩展方法,因此它们的实用性似乎有些受限.关于该主题的网络参考资料很少,因此显然没有多少人使用它们.这是一对夫妇:-
http://ayende.com/Blog/archive/2005/10/05/StaticGenericClass.aspx
<小时>给出的答案摘要
关键问题似乎是具有静态方法的静态泛型类和具有静态泛型成员的非泛型静态类之间有什么区别?">
关于使用哪个的决定似乎围绕着类是否需要在内部存储特定于类型的状态?"
如果不需要特定于类型的内部存储,那么具有通用静态方法的静态非通用类似乎更可取,因为调用语法更好,您可以在其中定义扩展方法.
我使用静态泛型类来缓存反射密集型代码.
假设我需要构建一个实例化对象的表达式树.我在类的静态构造函数中构建一次,将其编译为 lambda 表达式,然后将其缓存在静态类的成员中.我通常不会公开评估这些课程——它们通常是其他课程的助手.通过以这种方式缓存我的表达式,我避免了在某种Dictionary
中缓存我的表达式的需要.
BCL 中有此模式的示例.(DataRow
) 扩展方法 Field
和 SetField
使用(私有)静态泛型类 System.Data.DataRowExtensions+UnboxT
.用反射器检查一下.
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.
public static class Example<T>
{
public static ...
}
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
Static Generic Class as Dictionary
Summary of Answers Given
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.
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>
.
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屋!