How can I use Console.Write in object initializer?

前端 未结 2 1754
被撕碎了的回忆
被撕碎了的回忆 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:17

    You can't because Console.Write is not an accessible property or field of Karmand. You can only set values of class properties and fields in object initializers.

    Your code is a syntactic sugar (a little bit different) for the code below.

    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());
    

    You can have a constructor inside Karmand class to print that for you if you want.

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

    and then use it like

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

提交回复
热议问题