基元属性

以下示例定义了名为 Number 的基元属性。
[C#]
private int number = 0;
[Description("A nonnegative integer")]
public int Number
{
    get
    {
        if (number < 0) return 0;
        return number;
    }
    set
    {
        if (value < 0) number = 0;
        else number = value;
    }
}

枚举属性

当属性是枚举类型时,定义该属性类型的语法与其他基元属性类型的语法相同;但是,设置属性的页语法是不同的。以下代码片段定义了名为 Position 的枚举类型。
[C#]
public enum Position
{
    Forward = 0,
    Mid = 1,
    Defence = 2,
    Goalee = 3,
}

以下代码片段说明了公布 Position 类型属性的一个控件 (SoccerPlayer)
[C#]
public class SoccerPlayer : Control

    private Position position;
    ...
    // PlayerPosition is an enumeration property whose
    // type is the Position enumeration.
    [Description("The position of the player on the field.")]
    public Position PlayerPosition
    {
        get
        {
            return position;
        }
        set
        {
            position = value;
        }
    }
    ...
}

类属性

如果类 A 有一个类型为类 B 的属性,则 B 的属性(如果有)称为 A 的子属性。

以下代码片段定义了名为 Address 的类,它公开四个属性,每个属性的类型均为 String。

[C#] // The Address class. 

public class Address
{
private string street = null;
private string city = null;
private string state = null;
private string zip = null;
// The Street property.
public string Street
{
get{...}
set{...}
}
// The City property.
public string City
{
get{...}
set{...}
}
// The State property.
public string State
{
get{...}
set{...}
}
// The Zip property.
public string Zip
{
get{...}
set{...}
}
}
以下代码片段定义了名为 SoccerPlayer 的控件,它公开了一个类型为类 Address 的属性。
       
[C#] public class SoccerPlayer : Control 

{
private Address address = new Address();
// PlayerAddress is complex property whose
// type is the class Address. Address has four
// properties, Street, City, State, and Zip. These become
// subproperties of SoccerPlayer.
public Address PlayerAddress
{
get
{
return address;
}
// Note that the set accessor is not defined.
// The get accessor provides a handle to a PlayerAddress
// instance that can be used to set a subproperty such as
// PlayerAddress.Street.
}
}


posted on 2005-10-08 10:27  宝气狗  阅读(144)  评论(0)    收藏  举报