如何使用对象初始值设定项初始化对象(C# 编程指南)How to initialize objects by using an object initializer (C# Programming Guide)

可以使用对象初始值设定项以声明方式初始化类型对象,而无需显式调用类型的构造函数。You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

以下示例演示如何将对象初始值设定项用于命名对象。The following examples show how to use object initializers with named objects. 编译器通过首先访问无参数实例构造函数,然后处理成员初始化来处理对象初始值设定项。The compiler processes object initializers by first accessing the parameterless instance constructor and then processing the member initializations. 因此,如果无参数构造函数在类中声明为 private,则需要公共访问的对象初始值设定项将失败。Therefore, if the parameterless constructor is declared as private in the class, object initializers that require public access will fail.

如果要定义匿名类型,则必须使用对象初始值设定项。You must use an object initializer if you're defining an anonymous type. 有关详细信息,请参阅如何在查询中返回元素属性的子集For more information, see How to return subsets of element properties in a query.

示例Example

下面的示例演示如何使用对象初始值设定项初始化新的 StudentName 类型。The following example shows how to initialize a new StudentName type by using object initializers. 此示例在 StudentName 类型中设置属性:This example sets properties in the StudentName type:

public class HowToObjectInitializers
{
    public static void Main()
    {
        // Declare a StudentName by using the constructor that has two parameters.
        StudentName student1 = new StudentName("Craig", "Playstead");

        // Make the same declaration by using an object initializer and sending
        // arguments for the first and last names. The parameterless constructor is
        // invoked in processing this declaration, not the constructor that has
        // two parameters.
        StudentName student2 = new StudentName
        {
            FirstName = "Craig",
            LastName = "Playstead"
        };

        // Declare a StudentName by using an object initializer and sending
        // an argument for only the ID property. No corresponding constructor is
        // necessary. Only the parameterless constructor is used to process object
        // initializers.
        StudentName student3 = new StudentName
        {
            ID = 183
        };

        // Declare a StudentName by using an object initializer and sending
        // arguments for all three properties. No corresponding constructor is
        // defined in the class.
        StudentName student4 = new StudentName
        {
            FirstName = "Craig",
            LastName = "Playstead",
            ID = 116
        };

        Console.WriteLine(student1.ToString());
        Console.WriteLine(student2.ToString());
        Console.WriteLine(student3.ToString());
        Console.WriteLine(student4.ToString());
    }
    // Output:
    // Craig  0
    // Craig  0
    //   183
    // Craig  116

    public class StudentName
    {
        // This constructor has no parameters. The parameterless constructor
        // is invoked in the processing of object initializers.
        // You can test this by changing the access modifier from public to
        // private. The declarations in Main that use object initializers will
        // fail.
        public StudentName() { }

        // The following constructor has parameters for two of the three
        // properties.
        public StudentName(string first, string last)
        {
            FirstName = first;
            LastName = last;
        }

        // Properties.
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int ID { get; set; }

        public override string ToString() => FirstName + "  " + ID;
    }
}

对象初始值设定项可用于在对象中设置索引器。Object initializers can be used to set indexers in an object. 下面的示例定义了一个 BaseballTeam 类,该类使用索引器获取和设置不同位置的球员。The following example defines a BaseballTeam class that uses an indexer to get and set players at different positions. 初始值设定项可以根据位置的缩写或每个位置的棒球记分卡的编号来分配球员:The initializer can assign players, based on the abbreviation for the position, or the number used for each position baseball scorecards:

public class HowToIndexInitializer
{
    public class BaseballTeam
    {
        private string[] players = new string[9];
        private readonly List<string> positionAbbreviations = new List<string>
        {
            "P", "C", "1B", "2B", "3B", "SS", "LF", "CF", "RF"
        };

        public string this[int position]
        {
            // Baseball positions are 1 - 9.
            get { return players[position-1]; }
            set { players[position-1] = value; }
        }
        public string this[string position]
        {
            get { return players[positionAbbreviations.IndexOf(position)]; }
            set { players[positionAbbreviations.IndexOf(position)] = value; }
        }
    }

    public static void Main()
    {
        var team = new BaseballTeam
        {
            ["RF"] = "Mookie Betts",
            [4] = "Jose Altuve",
            ["CF"] = "Mike Trout"
        };

        Console.WriteLine(team["2B"]);
    }
}

请参阅See also