可以看到除了私有变量的地方不同外其它的都是一样的。
看看这俩变量的定义有什么不同。
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 )
好了现在放心了,大胆使用吧。
自动属性最终带给我们的应该是两种方式交融的编码方式
public class b { private int _age; public int ID { get; protected set; } public string Name { get; set; } public int Age { get { return _age; } set { if (value < 0 || value > 120) new Exception("年龄超出范围。"); else _age = value; } } public b(int id) { this.ID = id; } }