C#之构造函数

发表于:2011-12-27 10:18

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:佳园    来源:51Testing软件测试网采编

分享:
    public class Test
    {
        
static int i;
        
static  Test()
        {
            i 
= 1;
            Console.WriteLine(
"I am Test 静态默认构造函数 i={0}", i);
        }
        
public Test()
        {
            Console.WriteLine(
"I am Test 公有默认构造函数 i={0}", i);
        }
    }
    
public class ProgramTest
    {
        
static void Main(string[] args)
        {
            Test t1 
= new Test();
            Console.Read();
        }
    }

结果:I am Test 静态默认构造函数 i=1

     I am Test 公有默认构造函数 i=1

  如果静态默认构造函数和公有有参构造函数同时存在,我实例化类让它调用静态默认构造函数会怎么样呢?

 public class Test
    {
        
static int i;
        
static  Test()
        {
            i 
= 1;
            Console.WriteLine(
"I am Test 静态默认构造函数 i={0}", i);
        }
        
public Test(int j)
        {
            Console.WriteLine(
"I am Test 公有有参构造函数 i={0}", j);
        }
    }
    
public class ProgramTest
    {
        
static void Main(string[] args)
        {
            Test t1 
= new Test();  //系统会提示错误      
            Console.Read();

        }

    }

  如果静态默认构造函数和公有有参构造函数同时存在,我实例化类让它调用公有构造函数会怎么样呢?

    public class Test
    {
        
static int i;
        
static  Test()
        {
            i 
= 1;
            Console.WriteLine(
"I am Test 静态默认构造函数 i={0}", i);
        }
        
public Test(int j)
        {
            Console.WriteLine(
"I am Test 公有有参构造函数 i={0}", j);
        }
    }
    
public class ProgramTest
    {
        
static void Main(string[] args)
        {
            Test t1 
= new Test(2);
            Console.Read();
        }
    }

结果:I am Test 静态默认构造函数 i=1
     I am Test 公有有参构造函数 j=2

相关链接:

浅谈C#结构

浅谈C#继承

浅谈C#接口

44/4<1234
重磅发布,2022软件测试行业现状调查报告~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2023
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号