理解c#的Get Set访问器及测试脚本中的应用

假设我们需要定义一个新的数据类型,并要创建这种类型的变量,赋值,应用。

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;
            }

  

posted @ 2019-03-13 23:56  samma2018  阅读(152)  评论(3编辑  收藏  举报