C#属性学习日志

属性的定义:其实属性是字段和方法的一个交集---看起来像是一个字段,行为上又像一个方法。一个属性可以包含两个代码块,分别为get和set关键字开头,其实,get块包含的事在读取属性时要执行的语句(取值代码);set块包含的是向属性写入时要执行的语句(赋值语句)。


为结构或者类声明一个可读/可写的属性:

struct ScreenPosition
{
    ...
    public int X
    {
        get { ... }
        set { ... }
    }
    ...
}

 

为结构或者类声明一个只读的属性:

struct ScreenPosition{    
    ...   
    public int X    
    {        
    get { ... }            
    }    
    ...
}

 

为结构或者类声明一个只写的属性:

struct ScreenPostion{
    ...
    public int Y
    {
    set{ ...}
    }
    ...
}

 

在接口中声明一个属性:

interface IScreenPosition
{
    int X { get; set; } // no body
    int Y { get; set; } // no body
}

 

在结构或者类中实现一个接口属性:

struct ScreenPosition : IScreenPosition
{
    public int X
    {
        get { ... }
        set { ... }
    }
    public int Y
    {
        get { ... }
        set { ... }
    }
}

附上Visual C# 2010上的一个例子:

using System;
using System.Collections.Generic;
using System.Text;

namespace AutomaticProperties
{
    class Program
    {

        static void DoWork()
        {
            // to do
            Polygon square = new Polygon();
            Polygon triangle = new Polygon { NumSides = 3 };
            Polygon pentagon = new Polygon { NumSides = 5, SideLength = 15.5 };
            Console.WriteLine("Square:number of side is {0},length of each side is {1}",square.NumSides,square.SideLength);
            Console.WriteLine("Triangle:number of side is {0},length of each side is {1}", triangle.NumSides, triangle.SideLength);
            Console.WriteLine("Pentagon:number of side is {0},length of each side is {1}", pentagon.NumSides, pentagon.SideLength);

        }

        static void Main(string[] args)
        {
            try
            {
                DoWork();
               
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值