• 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"
                }
            }
        }
    }
  • 相关阅读:
    libcurl库进行http通讯-开篇
    hdu4059The Boss on Mars 容斥原理
    “最大子序列和”算法 java
    Android 的事件传递机制,详解
    POJ
    hdu 5652 India and China Origins
    解决Swap file &quot;.ceshi.c.swp&quot; already exists!问题
    3DMax脚本插件--改动材质&amp;贴图名称
    ASP.NET MVC+Bootstrap 实现短信验证
    [从头学数学] 第176节 概率
  • 原文地址:https://www.cnblogs.com/snake1118/p/10330030.html
Copyright © 2020-2023  润新知