我是C#的新手,前几天我遇到了一些代码问题,你们可能会帮助我。我在附加的代码中出错了。当你回答时,请理解它。我大学的课程名为"基础面向对象编程"。我的代码中出现了这个错误:
namespace Tennis_Player
{
class Player
{
private string first_name;
private string last_name;
private DateTime dob;
private string nat;
private char gender;
public Player(string first_name, string last_name, DateTime dob, string nat, char gender)
{
this.first_name = first_name;
this.last_name = last_name;
this.dob = dob;
this.nat = nat;
this.gender = gender;
}
public override string ToString() { return first_name + " " + last_name + " " +dob; }
static void Main(string[] args)
{
var Niels = new Player("Niels", "Olsen", 1985 - 12 - 25, "Denmark", 'M');
Console.WriteLine("Den nye spiller er " + Niels);
}
}
}
答案 0 :(得分:8)
不以这种方式传递日期时间值。从编译器的角度来看,您正在编写数学表达式 1985-12-25 (等于1948)并尝试将该数字传递给期望该参数的DateTime的方法。
您需要声明一个DateTime变量并使用您的infos
进行初始化static void Main(string[] args)
{
DateTime dob = new DateTime(1985,12,25);
var Niels = new Player("Niels", "Olsen", dob, "Denmark", 'M');
Console.WriteLine("Den nye spiller er " + Niels);
}
当然您也可以通过电话
创建日期时间static void Main(string[] args)
{
var Niels = new Player("Niels", "Olsen",
new DateTime(1985,12,25),
"Denmark", 'M');
Console.WriteLine("Den nye spiller er " + Niels);
}
请参阅MSDN上的DateTime structure
答案 1 :(得分:1)
您在新Player(...)构造函数中传递的DateTime格式无效。请尝试使用此代码:
static void Main(string[] args)
{
var dob = new DateTime(1985,12,25);
var Niels = new Player("Niels", "Olsen", dob, "Denmark", 'M');
Console.WriteLine("Den nye spiller er " + Niels);
}
答案 2 :(得分:1)
通过出生日期如下
DateTime dateofbirth = new DateTime(1985,12,25);
var player= new Player("Niels", "Olsen", dateofbirth , "Denmark", 'M');
Console.WriteLine("Den nye spiller er " + player);
Console.ReadLine();
答案 3 :(得分:0)
在您的代码中,您尚未将DateTime传递给正确的格式。请按照以下代码。
class Player
{
private string first_name;
private string last_name;
private DateTime dob;
private string nat;
private char gender;
public Player(string first_name, string last_name, DateTime dob, string nat, char gender)
{
this.first_name = first_name;
this.last_name = last_name;
this.dob = dob;
this.nat = nat;
this.gender = gender;
}
public override string ToString() { return first_name + " " + last_name + " " + dob; }
}
class Program
{
static void Main(string[] args)
{
var Niels = new Player("Niels", "Olsen", new DateTime(1985,04,11), "Denmark", 'M');
Console.WriteLine("Den nye spiller er " + Niels);
}
}