.Net3.0中的自動屬性(樣本)

來源:互聯網
上載者:User
using System;

namespace LinqDemo
{

    class Program
    {
        static void Main(string[] args)
        {
            //傳統用法樣本
            Employee Emp = new Employee("Jimmy.Yang", 25);
            Console.WriteLine(Emp.ToString());

            Console.WriteLine("-------------------");

            //自動屬性的寫法
            NewEmployee NewEmp = new NewEmployee { Name = "Tom", Age = 30 };//感覺與Javascript中對象的JSON字串標記法相似
            Console.WriteLine(NewEmp.ToString());

            Console.ReadLine();
        }       
    }


    /**//// <summary>
    /// 傳統方式定義一個類
    /// </summary>
    public class Employee
    {
        private string _name = "Anonymous";
        private int _age = 0;

        public string Name 
        {
            get { return this._name; }
            set { this._name = value; }
        }

        public int Age 
        {
            get { return this._age; }
            set { this._age = value; }
        }

        public Employee() { }

        public Employee(string pName, int pAge) 
        {
            this._name = pName;
            this._age = pAge;
        }

        public override string ToString()
        {
            return "Name:" + this._name + " Age:" + this._age;
        }
    }


    /**//// <summary>
    /// .Net3.0自動屬性的新寫法
    /// </summary>
    public class NewEmployee
    {
        public string Name{get; set;}
        public int Age { get; set; }
        public override string ToString()
        {
            return "Name:" + this.Name + " Age:" + this.Age;
        }
    }
}

可以看出,.Net3.0的自動屬性,可以使定義一個類的代碼大大減化,個人感覺:這一點好象又是從Javascript中的JSON字串標記法“偷”來的^_^,不信的話,可以參看以下Javascript代碼:

<script type="text/javascript">
var Emp = {Name:"Jimmy.Yang",Age:30};

function ShowEmp(E)
{
    return "Name:" + E.Name + " Age:" + E.Age;
}

document.write(ShowEmp(Emp));

</script>

順便發表一下個人感慨:微軟確實很善於吸引他人長處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.