C#3.0 automatic properties
来源:互联网 发布:涉及大数据的上市公司 编辑:程序博客网 时间:2024/05/22 15:24
C#3.0新增加了automatic properties(自动属性)特性,主要是减少了private field的typing,直接用{get;set}来代替原来的语句块。当一个类含有大量的private field时还是比较有用的。
C#2.0
class Player
...{
private string name;
public string Name
...{
get ...{ return name; }
set ...{ name = value; }
}
private int power;
public int Power
...{
get ...{ return power; }
set ...{ power = value; }
}
public Player(string p_name, int p_power)
...{
this.name = p_name;
this.power = p_power;
}
}
...{
private string name;
public string Name
...{
get ...{ return name; }
set ...{ name = value; }
}
private int power;
public int Power
...{
get ...{ return power; }
set ...{ power = value; }
}
public Player(string p_name, int p_power)
...{
this.name = p_name;
this.power = p_power;
}
}
现在可以用C#3.0
class Player
...{
public string Name ...{ get; set; }
public int Power ...{ get; set; }
public Player(string p_name,int p_power)
...{
this.Name = p_name;
this.Power = p_power;
}
}
...{
public string Name ...{ get; set; }
public int Power ...{ get; set; }
public Player(string p_name,int p_power)
...{
this.Name = p_name;
this.Power = p_power;
}
}
很明显,代码量减少了很多。不过这样做也是有限制的,如果这样写的话,一定要把get和set都写出来,就是说不能设成只读或只写,当然也不能在get,set里加入其它逻辑代码或try-catch。
NOTE THAT,自动属性并不同于public字段! 这一点我们可以用ILDASM来查看:
可以看到图中的get_Name等方法,说明Name是property,还有private字段的命名规则<>k__。具体可以看http://community.bartdesmet.net/blogs/bart/archive/2007/03/03/c-3-0-automatic-properties-explained.aspx
- C#3.0 automatic properties
- C# 3.0 的自动属性(Automatic Properties)
- C# 3.0 的自动属性(Automatic Properties)
- C# 3.0 的自动属性(Automatic Properties)
- C# 3.0 的自动属性(Automatic Properties)
- C# 3.0 的自动属性(Automatic Properties)
- C# 3.0 的自动属性(Automatic Properties)
- Automatic Properties in C#
- C#3.0新特性系列:自动属性(Automatic Properties)
- 新的C#语言特性:自动属性(Automatic Properties)
- C# 3.0新特性之Automatic Properties(自动属性)、Object Initializers(对象初始化器)、Collection Initializers(集合初始化器)和Extension Methods(扩展方法)
- VS2008&C#3.5语言特色系列[视频]:自动属性(Automatic Properties)
- 步步为营VS 2008 + .NET 3.5(3) - C# 3.0新特性之Automatic Properties(自动属性)、Object Initializers(对象初始化器)、Collection Initializers(集合初始化器)和Ext
- 步步为营VS 2008 + .NET 3.5(3) - C# 3.0新特性之Automatic Properties(自动属性)、Object Initializers(对象初始化器)、Collection Initializers(集合初始化器)和Ext
- C#读取properties文件
- C# Properties.Settings
- C#读取properties文件
- C# 3.0新特性之自动属性(Auto-Implemented Properties)
- Java初学者都必须理解的六大问题(转载)
- 。net的基础概念
- UBB解析优化的心得:Regex构造函数的性能
- Comparable排序
- "Illegal group reference"异常的分析
- C#3.0 automatic properties
- Series 60 3rd上绘图时设置字体的大小
- 生命的价值
- Asp.Net常见问题及技术实现方案(一)
- 何去何从-------------大家给个建议吧
- WebService介绍(一):创建WebService
- 无题
- Open XML API 之 Hello World
- squid的文件描述符