Static constructor in Generic Class


In Generic Class, when in the process of generic instantiation, static constructor will be called once for different types, even only creating a single code for all reference types. It is not difficult to understand, static constructor will be called when a new type is required.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication5
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            MyClass
<string> m1 = new MyClass<string>();

            MyClass
<int> m2 = new MyClass<int>();

            MyClass
<object> m3 = new MyClass<object>();
            MyClass
<object> m4 = new MyClass<object>(); // not call static constructor again

            MyClass
<StringBuilder> m5 = new MyClass<StringBuilder>();

            Console.ReadLine();
        }

    }


    
    
class MyClass<T>
    
{
        
static MyClass()
        
{
            Console.WriteLine(
typeof(T).Name);
        }

    }



}


So, we could take use of  static constructor to do some validation of T, such as T must have an attribute,  which is not easy to implement by generic constraint. Of course, generic constraint will be checked in compile phrase, but this will be in runtime phrase instead.

posted on 2007-07-20 13:08  redpeachsix  阅读(810)  评论(0编辑  收藏  举报

导航