构造函数
实例构造函数
csharp
internal class Course
{
private int id;
public int CourseId
{
get { return id; }//属性访问器 获取属性
set { id = value; }//设置属性
}
public string CourseName { get; set; }
public void ShowCourse()
{
Console.WriteLine("courseid is:" + CourseId + ",CourseName is:" + CourseName);
}
//不写修饰符,默认private 类,方法
public Course() { }
public Course(int id,string courseName)
{
CourseId=id;
CourseName=courseName;
}
}
csharp
Course course1 = new Course(22,"sds");
course1.CourseName = "CS";
course1.ShowCourse();

密封类构造
csharp
//public sealed class ChildClass
//{ }
//public class SubClass:ChildClass { }//密封类无法被继承

静态构造函数
csharp
public class Teacher
{
public static int count = 0;
public Teacher()
{
count = 1;
}
static Teacher()
{
count = 3;
}
}
csharp
//静态构造函数
Console.WriteLine($"count={Teacher.count}");//为什么不输出count=0
Teacher teacher = new Teacher();
Console.WriteLine($"count={Teacher.count}");




私有构造
csharp
public class Fav
{
private Fav()
{//单例模式的对象创建使用
}
public static Fav instance { get; set; } = new Fav();
}
public class RecordInfo
{
private static RecordInfo record = null;
private RecordInfo()
{
}
public static RecordInfo GetObj()
{
if(record == null)
{
record= new RecordInfo();
}
return record;
}
}
csharp
//私有构造
Fav v1 = Fav.instance;
RecordInfo record1 = RecordInfo.GetObj();
RecordInfo record2 = RecordInfo.GetObj();



this
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C_Up
{
public class Product
{
public Product()
{
Console.WriteLine("构造方法:Product对象");
}
private int Id;
public string ProductName { get; set; }
public int[] noArr = new int[5];
public Product(int id, string name)
{
this.Id = id;
this.ProductName = name;
}
//串联构造函数
public Product(string name) : this(0, name)
{
Console.WriteLine("名称:" + name);
Console.WriteLine("通过名称构造product");
}
public void Show()
{
Console.WriteLine("num is:" + Id + ";name is:" + ProductName);
}
public void SetNos(int[] nos)
{
if (nos.Length == 5)
{
for (int i = 0; i < nos.Length; i++)
{
{
noArr[i] = nos[i];
}
}
}
}
}
}
csharp
Product p1 = new Product(1, "玩具");
p1.Show();
Product p2 = new Product("枪");
