本文介绍了C#泛型静态构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将在泛型类的静态构造函数来运行所有类型的传递到通用参数,像这样的:

 类SomeGenericClass< T> 
{
静态列表< T> _someList;
静态SomeGenericClass()
{
_someList =新的List< T>();
}
}



是否有任何借鉴的背上用这种方法?


解决方案

是的,静态构造函数将被调用一次为每个封闭类类型(如果指定类型参数创建的类型)。请参阅 C#3规范,§10.12静态构造函数。



and also:

class Gen<T> where T: struct
{
    static Gen() {
        if (!typeof(T).IsEnum) {
            throw new ArgumentException("T must be an enum");
        }
    }
}

It is also relevant to read §4.4.2 Open and closed types:

This program that you can run yourself demonstrates that the static constructor is called three times, not just once:

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>();
    }
}

Output:

System.Int32
System.String
Program+Baz

这篇关于C#泛型静态构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 02:15