How can I use Console.Write in object initializer?

痴心易碎 提交于 2020-07-03 06:46:48

问题


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

Error CS0747 Invalid initializer member declarator

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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/37018595/how-can-i-use-console-write-in-object-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!