zoukankan      html  css  js  c++  java
  • C#杂记-简化的初始化

    对象说明

    public class Person
    {
        public int Age{get; set;}
        public string Name{get; set;}  
        
        List<Person> friends = new List<Person>();
        public List<Person> Friends {get{ return friends;} }
    
        Location home = new Location();
        public Location Home{ get {return home;}}
    
        public Person(){}
        public Person(string name)
        {
            Name = name;
        }
    }
    
    public class Location
    {
        public string Country {get; set;}
        public string Town {get; set;}
    }
    View Code

    --------------------------

    初始化

    Person tom1 = new Person();
    tom1.Age=10;
    tom1.Name="Tom";
    
    Person tom2 = new Person("Tom");
    tom2.Age=10;

    这是最典型的两种对象初始化的表达式。一种使用无参构造函数,一种使用有参构造函数。

    对象初始化加上属性赋值的多语句能用一条语句写出来吗?

    可以。对象初始化表达式

    Person tom3 = new Person(){ Name="Tom",Age=10};
    Person tom4 = new Person("Tom"){Age=10};
    person tom5 = new Person{Name="Tom",Age=10};

    一行代码实现了多行代码的操作,用的是表达式,可以干很多事情的。

    Person[] family = new Person[]
    {
        new Person{Name="1",Age=1},
        new Person{Name="2",Age=2},
        new Person{Name="3",Age=3},
        new Person{Name="4",Age=4}
    };

    嵌套对象的初始化

    Person tom = new Person
    {
        Name="Tom",
        Age = 10,
        Home = {Town = "a" , Country = "b"},
        Friends = 
        {
            new Person{Name="a",Age=10},
            new Person
            {
                Name="b",
                Age = 10,
                Home=
                {
                     Town = "b",
                     Country = "c"
                }
            }
        }
    }
  • 相关阅读:
    pl2303 驱动
    tomcat 启动脚本
    Linux下Shell命令加减乘除计算
    定时删除文件夹"$1"下最后修改时间大于当前时间"$2"天的文件
    mysql 拼接字符
    jquery iframe父子框架中的元素访问方法
    在线工具
    js对数组对象的操作以及方法的使用
    HTML 设置字体
    10月1号 备忘录
  • 原文地址:https://www.cnblogs.com/snake1118/p/10330030.html
Copyright © 2011-2022 走看看