如何在对象初始值设定项中使用Console.Write?

sal*_*ian 4 .net c# object-initializers

当我Console.Write在对象初始化程序中使用时,我收到此错误

错误CS0747初始化程序成员声明符无效

person[i] = new Karmand()
            {
                Console.Write("first name:"),
                FirstName = Console.ReadLine(),
                LastName = Console.ReadLine(),
                ID = Convert.ToInt32(Console.ReadLine()),
                Hoghoogh = Convert.ToDouble(Console.ReadLine())
            };
Run Code Online (Sandbox Code Playgroud)

Ham*_*jam 6

你不能因为Console.Write不是一个可访问的财产或领域Karmand.您只能在对象初始值设定项中设置类属性和字段的值.

你的代码是下面代码的语法糖(有点不同).

var person[i] = new Karmand();
// what do you expect to do with Console.Write here?
person[i].FirstName = Console.ReadLine();
person[i].LastName = Console.ReadLine();
person[i].ID = Convert.ToInt32(Console.ReadLine());
person[i].Hoghoogh = Convert.ToDouble(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

你可以在Karmand类中有一个构造函数,如果你愿意,可以为你打印.

public class Karmand
{
    public Karmand(bool printFirstName = false)
    {
        if (printFirstName)
            Console.Write("first name:");
    }

    // rest of class code
}
Run Code Online (Sandbox Code Playgroud)

然后像使用它一样

person[i] = new Karmand(printFirstName: true)
            {
                FirstName = Console.ReadLine(),
                LastName = Console.ReadLine(),
                ID = Convert.ToInt32(Console.ReadLine()),
                Hoghoogh = Convert.ToDouble(Console.ReadLine())
            };
Run Code Online (Sandbox Code Playgroud)