1. 程式人生 > >理解c#的Get Set訪問器及測試腳本中的應用

理解c#的Get Set訪問器及測試腳本中的應用

document element 項目 for .get 讀取 定義 種類 實戰

假設我們需要定義一個新的數據類型,並要創建這種類型的變量,賦值,應用。

1. 理解概念:

先通過一個生動的例子來理解概念: 創建一個Cat類,其中定義私有屬性(又名字段),和屬性。

    class Cat
    {
        private string name;
        private int age;
        private string sex;

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

        public int Age //get訪問器get到並返回該字段age的值。set訪問器給這個字段賦值
        {
            get { return this.age; }
            set { this.age = value; }
        }

        public string Sex
        {
            get { return this.sex; }
            set { this.sex = value; }
        }
    }

  當要實例化一個cat類的對象時,可以理解為生一只小貓時,可以給新生的小貓的屬性賦值,如:

    class Program
    {
        static void Main(string[] args)
        {
            Cat babyCat = new Cat();
            babyCat.Name = "xiaominhg";
            babyCat.Age = 2;
            babyCat.Sex = "female";
            //$是string.format中的新特性
            string msg = $"I‘m a new born baby cat, " +
                $"my name is {babyCat.Name}, my age is {babyCat.Age}, " +
                $"my sex is {babyCat.Sex}";
            Console.WriteLine(msg);
            Console.ReadKey();
        }
    }

  運行結果:I‘m a new born baby cat, my name is xiaominhg, my age is 2, my sex is female

2. 項目中實戰:

最近的項目中需要加一個小功能,從xml文件裏讀取一個節點上的3個屬性的值(a,b,c),遍歷所有節點。最後返回遍歷的所有結果。

思路:

1. 定義一個class來定義數據模型

    public class ValueNeed
    {
        private string a;
        private string b;
        private string c;

        public string A
        {
            get { return this.a; }
            set { this.a= value; }
        }

        public string B
        {
            get { return this.b; }
            set { this.b= value; }
        }

        public string C
        {
            get { return this.c; }
            set { this.c= value; }
        }

2. 實際項目中,需要把這個類型的數據每次遍歷的結果放入List中,返回所有遍歷結果。於是定義一個List<ValueNeed> TestFunction() 方法,在其中執行遍歷,並返回List類型的該數據模型的數據。

3. 實例化這個類,創建新的數據對象,並獲取需要的屬性,賦值。

            {
                string path = xmlFilePath;
                XDocument doc = XDocument.Load(path);
                var node1= doc.Root.Elements(XName.Get("value1"));
                
                List<ValueNeed> returnResult = new List<ValueNeed>();

                foreach (var node in node1)
                {
                    ValueNeed xxx= new ValueNeed ();
                    xxx.a= node.Attribute(XName.Get("a")).Value;
                    xxx.b= node.Attribute(XName.Get("b")).Value;
                    xxx.c= node.Attribute(XName.Get("b")).Value;

                    returnResult.Add(xxx);
                }

                return returnResult;
            }

  

理解c#的Get Set訪問器及測試腳本中的應用