C#3.0 为我们带来什么(2) —— 自动属性
public int ID { get; protected set; }
public string Name { get; set; }
这是接口内声明的属性么?
no,这也可以是类的属性,自动属性。
如果说c#3.0最大的改变是什么,那就是编码方式更人性化,程序员可以变的更懒。自动属性也是这一特征的具体表现。
对比两段代码
C# 2.0

































C# 3.0









随3.0而来的自动属性使我们可以方便的定义一个简单属性(不需要对field进行特殊处理的),他所使用的私有变量由系统来生成。工作量减少,阅读难度降低。
下面来看看编译器到底为我们做了什么。
使用IL Disassembler来看看到底发生了什么。

可以看到除了私有变量的地方不同外其它的都是一样的。
看看这俩变量的定义有什么不同。
c# 2.0
.field private int32 _id
c# 3.0:
.field private int32 '<ID>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
反射?
msdn对CompilerGeneratedAttribute是这样描述的。
Distinguishes a compiler-generated element from a user-generated element. This class cannot be inherited.
区分编译器生成的元素与用户生成的元素。无法继承此类。
其意思就是上面两端IL代码没什么不同,不过是第二个里的私有变量标记了是编译器生成的而已。
再来看看两个个set_Name
c#2.0
.method public hidebysig specialname instance void
set_Name(string 'value') cil managed
{
// 代码大小 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: stfld string WindowsFormsApplication1.a::_name
IL_0008: ret
} // end of method a::set_Name
c#3.0:
.method public hidebysig specialname instance void
set_Name(string 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// 代码大小 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld string WindowsFormsApplication1.b::'<Name>k__BackingField'
IL_0007: ret
} // end of method b::set_Name
不同也不过是多了一句话
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
好了现在放心了,大胆使用吧。
自动属性最终带给我们的应该是两种方式交融的编码方式
























(小弟才疏学浅,欢迎各位看客指正错误。)