如何在对象初始化程序中使用Console.Write? [英] How can I use Console.Write in object initializer?
本文介绍了如何在对象初始化程序中使用Console.Write?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在对象初始化程序中使用Console.Write
时,出现此错误
When I use Console.Write
in object initializer I get this error
错误CS0747无效的初始化器成员声明器
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())
};
推荐答案
您不能,因为Console.Write
不是Karmand
的可访问属性或字段.您只能在对象初始值设定项中设置类属性和字段的值.
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());
如果需要,您可以在Karmand
类中有一个构造函数为您打印该构造函数.
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
}
然后像使用它
person[i] = new Karmand(printFirstName: true)
{
FirstName = Console.ReadLine(),
LastName = Console.ReadLine(),
ID = Convert.ToInt32(Console.ReadLine()),
Hoghoogh = Convert.ToDouble(Console.ReadLine())
};
这篇关于如何在对象初始化程序中使用Console.Write?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文