对象初始化器

  对象初始化器,就是简化代码,让本来几行写完的代码,一行就写完了

  使用对象初始值设定项,可以在创建对象时向对象的任何可访问的字段或属性分配值,而无须显示调用构造函数,其实对象初始化器最大的作用就是减少代码的书写量,把原本一些人做的事情交给了框架

  举例

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  namespace _13_ObjectInitializers
  {
      class Program
      {
          static void Main(string[] args)
          {
              Student stu = new Student { _name = "小强", Sex = "男", _age = 25 };
              Console.WriteLine(stu._name);
              Console.WriteLine(stu.Sex);
              Console.WriteLine(stu._age);
              Console.ReadKey();
          }
      }
      class Student
      {
          public string _name;
          public string Sex { get; set; }
          public int _age;
      }
  }

  运行效果

  C#温故而知新学习系列之面向对象编程—对象初始化器(十五)

 

 

相关文章:

  • 2021-08-01
  • 2021-07-30
  • 2021-11-12
  • 2022-12-23
  • 2021-07-16
  • 2021-08-14
  • 2021-05-26
  • 2022-01-26
猜你喜欢
  • 2021-09-04
  • 2021-07-31
  • 2021-11-10
  • 2021-12-01
  • 2021-12-11
  • 2022-03-09
  • 2022-02-11
相关资源
相似解决方案