namespace 类属性
{
class student
{
private string name;
private char sex;
private int age;
private int chinese;
private int math;
private int english;
public string Name
{
get { return name; }
set { name = value; }
}
public char Sex
{
get { return sex; }
set
{
if (value == '男' || value == '女')
{
sex = value;
}
else
{
sex = '男';
}
}
}
public int Age
{
get { return age; }
set { age = value >= 0 ? value : 0; }
}
public int Chinese
{
get { return chinese; }
set { chinese = value >= 0 ? value : 0; }
}
public int Math
{
get { return math; }
set { math = value >= 0 ? value : 0; }
}
public int English
{
get { return english; }
set { english = value >= 0 ? value : 0; }
}
public void sayhello()
{
// Console.WriteLine("我叫{0},我今年{1}岁了,我是{2}生", name, age, sex);
Console.WriteLine("我叫{0},我今年{1}岁了,我是{2}生", name, age, sex);
}
public void showscore()
{
int sum = chinese + math + english;
int avg = sum / 3;
// Console.WriteLine("我叫{0},我的总成绩是{1}分,平均成绩为{2}", name, sum, avg);
Console.WriteLine("我叫{0},我的总成绩是{1}分,平均成绩为{2}", name, sum, avg);
}
}
}
第二个代码如下:
class Program
{
static void Main(string[] args)
{
student zsStudent = new student();
zsStudent.Name="张三";
zsStudent.Sex='男';
zsStudent.Age =18;
zsStudent.Chinese=90;
zsStudent.Math=95;
zsStudent.English=80;
student xlstudent=new student();
xlstudent.Name="小兰";
xlstudent.Sex='女';
xlstudent.Age =16;
xlstudent .Chinese=95;
xlstudent .Math =85;
xlstudent .English=100;
Console.WriteLine("这是张三打招呼!");
zsStudent .sayhello();
zsStudent .showscore();
Console.WriteLine("这是小兰打招呼!");
xlstudent .sayhello();
xlstudent .showscore ();
Console.ReadKey();
}
}
我刚看了你程序,有几个问题:
1.你声明字段的时候没有访问限制,这样就失去了字段功效,变成类内部一个变量而已,更不能做限制。加上private后,不能从类外直接赋值与取值。这样能给属性在中间做一些处理,和你程序一样。
2.你说的问题,写的“我叫{0},我的总成绩是{1}分,平均成绩为{2}”,没有填入对应的值,是因为你的“{0}”大括号是在中文状态输入的,C#无法识别为标识符。你自己做下对比
|