上学时,我需要锻炼身体,但是没有一个老师愿意帮助我,因为我们在一起工作,所以我比他们走得更远,所以我需要等到他们到我为止。你们其中一个可以帮我吗?这是第一次使用这种C#。他们甚至从未向我们展示如何使用它,我也不知道该怎么办。
using System;
namespace Tracks
{
public class Class1
{
private int id;
private string name;
private string artist;
private string albumSource;
private Category style;
private Time length;
enum Category
{
Ambient = 0,
Blues = 1,
Country = 2,
Disco = 3,
Electro = 4,
Hardcore = 5,
HardRocck = 6,
HeavyMetal = 7,
Hiphop = 8,
Jazz = 9,
Jumpstyle = 10,
KLassiek = 11,
Latin = 12,
Other = 13,
Pop = 14,
Punk = 15,
Reggae = 16,
Rock = 17,
Soul = 18,
Trance = 19,
Techno = 20,
}
public struct Time
{
public int s, m, h;
public Time(int s1)
{
s = s1;
}
public Time(int s1, int m1)
{
s = s1;
m = m1;
}
public Time(int s1, int m1, int h1)
{
s = s1;
m = m1;
h = h1;
}
}
}
}
答案 0 :(得分:2)
由于Time
是struct
,因此所有字段都需要在构造函数中初始化。将您的前两个构造函数更改为以下内容:
public Time(int s1)
{
s = s1;
m = h = 0;
}
public Time(int s1, int m1)
{
s = s1;
m = m1;
h = 0;
}
甚至更好地将它们定义为:
public Time(int s1) : this(s1, 0, 0) {}
public Time(int s1, int m1) : this (s1, m1, 0) {}
public Time(int s1, int m1, int h1)
{
s = s1;
m = m1;
h = h1;
}
这样,您只能将对齐方式放在一个地方。
答案 1 :(得分:1)
如果您需要一个可以使用默认值调用的构造函数,则可以:
public Time(int s1, int m1 = 0, int h1 = 0)
{
s = s1;
m = m1;
h = h1;
}
您将可以这样称呼它:
Time( 1 );
Time( 1, 2 );
Time( 1, 2, 3 );