zoukankan      html  css  js  c++  java
  • Linq专题之对象初始化器

      在C#3.0之前,如果创建一个新的对象,往往需要调用类的构造函数来初始化该对象的值,在c#3.0提供了一个"对象初始化器"的机制,使得开发人员在创建新的对象时不通过调用类的构造函数,以声明的方式创建一个对象并初始化对象的值。看下面的例子:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Linq;
     6 
     7 namespace LinqDemo
     8 {
     9     class Program
    10     {
    11         static void Main(string[] args)
    12         {
    13 
    14             Test test = new Test() {UserId=1,UserName="IT少年",Age=26};
    15             Console.WriteLine("姓名:"+test.UserName);
    16             Console.WriteLine("年龄:"+test.Age);
    17 
    18             Console.ReadKey();
    19         }
    20 
    21        
    22     }
    23 
    24     public class Test
    25     {
    26 
    27        public int UserId;
    28 
    29        public string UserName;
    30 
    31        public int Age;
    32 
    33         public string Sex;
    34 
    35     }
    36 }

    我们看到在创建对象后,通过一对{}就可以给对象的public成员赋初始化值了。
    运行结果:

  • 相关阅读:
    ColorMask
    InfoPanel
    什么是三消游戏
    Display file information in the document window
    Layer Comps
    Add words to your picture
    为什么质数是无穷的?
    嘉年华的来历
    MonoBehaviour.OnValidate
    Loadrunner中百分比模式和Vuser模式
  • 原文地址:https://www.cnblogs.com/yplong/p/5386814.html
Copyright © 2011-2022 走看看