代码改变世界

c#进阶methods中

2010-12-23 15:54  撞破南墙  阅读(1873)  评论(0编辑  收藏  举报

 值类型实例的函数

值类型不需要构造函数也不会被默认添加,但是你可以为他定义带参构造函数。

结构体被使用后中变量被初始化为0/NULL.值类型可以直接赋值,当然也可以

使用构造函数赋值,但其构造函数不能为无参构造函数否则会报错

"error CS0568: Structs cannot contain explicit parameterless
constructors."

c#编译器这么做是为了让开发人员在构造函数调用这里少些困惑。

而因为值类型没有无参构造函数那么如下代码也一样不能执行(上)篇已经说了。

 

internal struct SomeValType { 
// You cannot do inline instance field initialization in a value type 
private Int32 m_x = 5
}

 

 

 

类型的构造函数

CLR不仅支持实例的构造函数,还支持  类型构造函数( static 构造函数 。类和机构体的构造函数),甚至是接口的构造函数(c#不支持)。

引用类型的构造函数

 

internal sealed class SomeRefType { 
static SomeRefType() { 
// This executes the first time a SomeRefType is accessed.
//首次进入此类型时执行 


值类型的构造函数
internal struct SomeValType { 
// C# does allow value types to define parameterless type constructors. 
static SomeValType() { 
// This executes the first time a SomeValType is accessed. 

}
当值类型的构造函数并未执行
internal sealed class SomeRefType { 
          
static SomeRefType() { 
                    Console.WriteLine(
"引用类型 的构造函数被 执行 "); 
      } 
  }
  
internal struct SomeValType { 
      
public static int _testint; 
      
static SomeValType() { 
          Console.WriteLine(
"值类型 的构造函数被 执行 "); 
      } 
  }
class Program { 
        
static void Main(string[] args) { 
            SomeRefType s 
= new SomeRefType(); 
            SomeValType[] svt 
= new SomeValType[1]; 
            Console.Read(); 
        } 
    }

 

 

image

 

测试发现,当使用实例构造函数的时候才会执行结构体里的类型构造函数。

另一个测试代码:

 

internal sealed class SomeRefType { 
       
public static int _testint; 
       
static SomeRefType() { 
           _testint 
= 1
           Console.WriteLine(
"引用类型的类型构造函数被执行"); 
       } 
       
public SomeRefType() { 
           Console.WriteLine(
"引用类型的实例的构造函数被执行"); 
       } 
   }
   
internal struct SomeValType { 
       
public static int Testint; 
       
static SomeValType() { 
           Console.WriteLine(
"值类型的类型构造函数被执行 "); 
       }
       
private string test; 
       
public SomeValType(string value) { 
           Console.WriteLine(
"值类型实例的构造函数被执行" + value); 
           test 
= value; 
       } 
   }
 
 
class Program { 
       
static void Main(string[] args) { 
           Display(
0); 
           SomeRefType s 
= new SomeRefType(); 
           Display(
1); 
           SomeRefType s2 
= new SomeRefType(); 
           Display(
2); 
           SomeValType[] svt 
= new SomeValType[1]; 
           Display(
3); 
           svt[
0= new SomeValType("test"); 
           Display(
4); 
           Console.Read(); 
       }
       
static void Display(object ob) { 
           Console.WriteLine(DateTime.Now.ToString() 
+"      "+ ob.ToString()); 
       } 
   }

 

 

以及他们的执行顺序  

image

 另外:由于类型的构造函数在程序中只会执行一次。所以可以利用它来做单例模式。