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;
        }


    }

现在可以用C#3.0

class Player
    
{
        
public string Name getset; }

        
public int Power getset; }

        
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

原创粉丝点击