C#私有构造函数
我们可以在C#中使用私有构造函数。私有构造函数是用私有说明符Private创建的。
在C#语言中,我们不能创建一个至少包含一个私有构造函数的类的实例。它们通常用于只包含静态成员的类中。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace defaultConstractor { public class like { private like() //private constrctor declaration { } public static int currentview; public static int visitedCount() { return ++ currentview; } } class viewCountedetails { static void Main() { //like r = new like(); //Error Console.WriteLine("-------Private constructor----------"); Console.WriteLine(); like.currentview = 100; like.visitedCount(); Console.WriteLine("Now the view count is: {0}", like.currentview); Console.ReadLine(); } } }
C# 复制构造函数
如果我们创建一个新对象并希望从现有对象复制值,则可以使用Copy构造函数。
复制构造函数的目的是将新实例初始化为现有实例的值。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProgramCall { class PEPSI { int A, B; public PEPSI(int X, int Y) { A = X; B = Y; } //Copy Constructor public PEPSI(PEPSI P) { A = P.A; B = P.B; } public void Print() { Console.WriteLine("A = {0}\tB = {1}", A, B); } } class CopyConstructor { static void Main() { PEPSI P = new PEPSI(10,11); //Invoking copy constructor PEPSI P1 = new PEPSI(P); P.Print(); P1.Print(); Console.Read(); } } }
日期:2020-04-11 23:03:41 来源:oir作者:oir