C# 问题一个。。期待回答。。

来源:百度知道 编辑:UC知道 时间:2024/06/08 18:32:05
我新建了一个类,名字:Person
代码如下:
class Person
{
public string Name = "";
protected int Age = 0;
public int GetAge(int age)
{
return Age;
}

}

又建了一个类,代码:
class Worker:Person
{
public new int SetAge(int age)
{

if (age >= 18)
{
return -1;
}
else
{
Age = age;
return 0;
}
}
}
然后我创建一个窗体。添加文本框和按钮textbox1和button1

请问如何让textbox1用来输入Worker的年龄,并且按钮用来设置Worker这个类的年龄呢?

class Person
{
public string Name = "";
protected int Age = 0;
public int GetAge
{
get{return age;}
set{age=value;}
}
}
引用的时候:
Person p=new Person();
p.GetAge=this.textbox1.Text;
取age的值:
int age=p.age;

Worker worker = new Worker();
int age = int.Parse(TextBox1.Text);
int r = worker.SetAge(age);
if(r == 0)
{
//设置成功
}
else
{
// 不符合年龄范围.难道worker不能大于18岁?你招童工吗
}

public string Name = "";
protected int Age = 0;
这里好像有错误,声明属性不能初始化。
public string Name ;
protected int Age ;
这样就可以了

你这里只是对年龄是否大于18进行判断,而不是要知道具体年龄吧.
还有,你的年龄是有Get,没有Set,所以说,是不可以赋值的