class Person
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
}前几天看别人的代码,才知道get,set块中的代码可以省略的,并且使用起来也没什么不同:
class Person
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}它们有什么区别呢?打开ildasm看了下:


很明显,省略get,set块中的代码后编译器自动声明两个字段<Name>k__BackingField和<Name>k__BackingField,等效于我们手工声明的name和age。再看下MSIL代码:
.method public hidebysig specialname instance string
get_Name() cil managed
{
// 代码大小 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld string ConsoleApplication1.Person::name
IL_0006: ret
} // end of method Person::get_Name
.method public hidebysig specialname instance void
set_Name(string 'value') cil managed
{
// 代码大小 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld string ConsoleApplication1.Person::name
IL_0007: ret
} // end of method Person::set_Name.method public hidebysig specialname instance string
get_Name() cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// 代码大小 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld string ConsoleApplication1.Person::'<Name>k__BackingField'
IL_0006: ret
} // end of method Person::get_Name
.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 ConsoleApplication1.Person::'<Name>k__BackingField'
IL_0007: ret
} // end of method Person::set_Name当然了,这么省略也是有前提条件的,那就是不需要对属性进行一些额外的处理,比如赋值时不需检测值的有效性,否则还是不能省略的。
评论(0)
暂无评论。