对于传递给泛型参数的每种类型,将在泛型类上运行静态构造函数,例如:
class SomeGenericClass<T>
{
static List<T> _someList;
static SomeGenericClass()
{
_someList = new List<T>();
}
}
使用这种方法有什么缺点吗?
最佳答案
是的,将为每个封闭类类型(指定类型参数时创建的类型)调用一次静态构造函数。请参见C# 3 specification,第10.12节静态构造函数。
并且:
class Gen<T> where T: struct
{
static Gen() {
if (!typeof(T).IsEnum) {
throw new ArgumentException("T must be an enum");
}
}
}
阅读第4.4.2节“打开和关闭”类型也很重要:
您可以自行运行的该程序演示了静态构造函数被调用了三次,而不仅仅是一次:
public class Program
{
class SomeGenericClass<T>
{
static SomeGenericClass()
{
Console.WriteLine(typeof(T));
}
}
class Baz { }
static void Main(string[] args)
{
SomeGenericClass<int> foo = new SomeGenericClass<int>();
SomeGenericClass<string> bar = new SomeGenericClass<string>();
SomeGenericClass<Baz> baz = new SomeGenericClass<Baz>();
}
}
输出:
System.Int32
System.String
程序+ Baz