C# 属性、匿名类型

//命名空间
namespace Common;

//类
internal class Program
{
    //程序入口
    static void Main(string[] args)
    {
        Person person = new Person();

        //使用属性赋值
        person.Name = "流川楓";
        person.Age = 16;
        person.Sex = (int)Sex.M;

        //結果:名前:流川楓、年齢:16、性別:1
        person.showPersonInfo();

        //使用属性取值
        string name = person.Name;
        int age = person.Age;

        //結果:名前:流川楓、年齢:16
        Console.WriteLine("名前:{0}、年齢:{1}", name, age);

        /************************************************************/
        //匿名类型
        var tmp = new Person();
        var num = 23;

        //結果:tmpのデータ型:Common.Person、numのデータ型:System.Int32
        Console.WriteLine("tmpのデータ型:{0}、numのデータ型:{1}", tmp.GetType(), num.GetType());
    }

    //enum类型
    public enum Sex
    {
        F = 0, M = 1
    }
}

/// <summary>
/// Person类
/// </summary>
internal class Person
{
    private string name;
    private int age;
    private int sex;

    //构造函数的名字要与类同名,没有返回值。
    //当没有定义构造函数时,类会默认创建一个无参的构造函数
    public Person() { }

    /// <summary>
    /// name属性声明
    /// </summary>
    public string Name 
    {
        //get,set可以简写
        get;set;
    }

    /// <summary>
    /// age属性声明
    /// </summary>
    public int Age
    { 
        get { return age; } 
        set 
        { 
            if(value > 0)
            {
                age = value;
            }
            
        }
    }

    /// <summary>
    /// sex属性声明
    /// </summary>
    public int Sex 
    {
        //属性可以设置访问权限符,未设定时,默认和属性声明同级
        private get { return sex; } 
        set { sex = value; } 
    }
    
    /// <summary>
    /// 信息显示
    /// </summary>
    public void showPersonInfo()
    {
        Console.WriteLine("名前:{0}、年齢:{1}、性別:{2}", this.name, this.age, this.sex);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值