C# 构造函数 属性 匿名类型
构造函数
用于初始化数据。
值类型默认值是0,引用类型默认值是null。
无返回值,函数名与类名保持一致,可重载。
为了方便创建,构造函数的参数名称往往和数据成员的名称一样,为了区分,可以使用this
关键字指代类的当前实例
1 internal class Customer 2 { 3 private string name; 4 private string address; 5 private int age; 6 private string createTime; 7 8 public Customer(string name,string address,int age,string createTime) 9 { 10 this.name = name; // this.name 指 Customer 类中的 name,而 name 是参数 11 this.address = address; 12 this.age = age; 13 this.createTime = createTime; 14 } 15 }
属性
要为每个数据成员设置对应get和set方法比较繁琐,使用属性可以简化操作。
1 internal class Customer 2 { 3 private string name; 4 private int age; 5 6 public int Age 7 { 8 get { return age; } 9 set { age = value; } 10 } 11 12 public string Name 13 { 14 private get { return name; } //可以设置访问权限,若不设置则与属性访问权限一致 15 //set { name = value; } //可以只有set或get,即只读或只写 16 } 17 18 public string Address{ get; set; } //自动创建string address成员 19 } 20 21 22 internal class Program 23 { 24 static void Main(string[] args) 25 { 26 // 属性的使用 27 lisi.Age = 55; 28 Console.WriteLine(lisi.Age); 29 30 lisi.Name = "里斯"; // 报错,Name属性无set方法 31 Console.WriteLine(lisi.Name); //报错,因为Name属性的get为private 32 } 33 }
匿名类型
直到赋值再给予相应的类型,给予后不再更改类型
1 var num = 22; 2 var str = "Hello World";
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!