C#构造函数用法

1.实例构造函数

2.静态构造函数

3.私有构造函数

例:

创建一个类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _20180718Demo
 8 {
 9     public class TestConstructor
10     {
11         public int a;
12         public int b;
13 
14         public static int c;
15 
16         //静态构造函数(不可带修饰符)
17         static TestConstructor()
18         {
19             Console.WriteLine("静态构造函数被调用!");
20         }
21 
22 
23         //无参构造函数
24         public TestConstructor()
25         {
26 
27         }
28 
29         public TestConstructor(int ia, int ib, int ic)
30         {
31             this.a = ia;
32             this.b = ib;
33         }
34 
35         public TestConstructor(int ia, int ib)
36         {
37             this.a = ia;
38             this.b = ib;
39         }
40 
41         public int Add()
42         {
43             return a + b;
44         }
45     }
46 }
View Code

1.在主函数种为静态变量c赋值并输出。

 System.Console.WriteLine(TestConstructor.c=99);

运行一下:如图所示:

结论:访问该静态变量之前被调用

2.在主函数种实例化TestConstructor类,并且调用Add()方法。

TestConstructor Tc = new TestConstructor(6, 2);
System.Console.WriteLine(Tc.Add());

运行一下,如图所示:

结论:①第一次实例化该类时,静态函数被调用

           ②构造函数可以进行重载,类实例化时可以为成员变量赋值

3.私有构造函数。使用场景(工具类、单例模式)

创建一个单例类:

 1   class SingleT
 2     {
 3         public static SingleT s = null;
 4         private SingleT()
 5         {
 6 
 7         }
 8 
 9         public static SingleT GetInstance() 
10         {
11           if(s==null)
12           {
13               return s = new SingleT();
14           }
15 
16           return s;
17         }
18     }
View Code

结论:私有构造函数,可用于直接阻止创建类的实例

参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/private-constructors

 

转载于:https://www.cnblogs.com/-xyl/p/9330038.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值