字段是私有的,一般在类内部使用。private
一般只用来储存数据
读写无限,(除了readonly)
属性是给外部使用的,公有的一般用public
属性可以在里面写一些业务逻辑
读写可以自定义,可控,安全性强
使用:一般在外部类调用时,使用属性,属性再把值储存在字段里。
public class Attribute { //private int id; public int Id { get;set; } public string Name { get; set; } = "guang"; private int age;//不要忘记加字段 public int Age { get{ return age; } set { if (value < 0) { //throw new Exception("年龄不能为负数!"); Console.WriteLine("年龄不能为负数!"); } else age = value;//把值赋给字段 } } //private int price; public int Price { get; } = 100; private string text; public string Text { get { return $"ID为:{Id},名字是:{Name},年龄为:{age},价格:{Price}"; } } public string Test() { string test = $"Id是{Id},名称为:{Name},年龄为:{Age},价格:{Price}"; return test; } }
public static void Attribute() { Attribute attribute= new Attribute(); attribute.Id = 1; attribute.Age = -9; Console.WriteLine(attribute.Test()); Console.WriteLine(attribute.Text); }
本文来自博客园,作者:阿霖找BUG,转载请注明原文链接:https://www.cnblogs.com/lin-07/p/17346672.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?