How can I use Console.Write in object initializer?

前端 未结 2 1773
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 23:05

When I use Console.Write in object initializer I get this error

Error CS0747 Invalid initializer member declarator

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-19 23:20

    Try removing Console.Write("first name:"). Console.Writeline is not an assignment to a property or a field.

    From MSDN

    An object initializer is used to assign values to properties or fields. Any expression which is not an assignment to a property or field is a compile-time error.

    To correct this error Ensure that all expressions in the initializer are assignments to properties or fields of the type.

    Update:
    If you need to use Console.Writeline, then use it before the object initializer like

    Console.Writeline("first name:");
    { person[i] = new Karmand()
                {
                    FirstName = Console.ReadLine(),
                    LastName = Console.ReadLine(),
                    ID = Convert.ToInt32(Console.ReadLine()),
                    Hoghoogh = Convert.ToDouble(Console.ReadLine())
                };
    

提交回复
热议问题