现在的位置: 首页 > 综合 > 正文

c#–结构属性字段错误

2013年02月17日 ⁄ 综合 ⁄ 共 1177字 ⁄ 字号 评论关闭
Ò编写一个存储老师属性的结构
É结构名称TeacherStruct
É姓名(teacherName)
É年龄(teacherAge)
É参加工作的年限(yearsOfService)
ÉSayHi方法(大家好,我是某某老师。我已经在教育战线奋斗了 几年了)
Ò调用这个结构显示它的数据
 
在这里,其实我们知道使用struct关键字来申明结构。当然。当我声明一个结构的时候。字段是不能赋值的。
 public struct  StructTeacher
    {
       public string teacherName;
       public int teacherAge;
       public int yearsofServices;
       public StructTeacher(string teachername, int teacherage, int yearsofservices)
       {
           this .teacherName=teachername;
           this .teacherAge=teacherage;
           this.yearsofServices =yearsofservices ;
       }
       public void sayHi(string teachername, int teacherage, int yearsofservices)
       {
           MessageBox.Show(string .Format("大家好,我是{0},今年{1}岁,我已经在教育战线上奋斗了{2}年了",this.teacherName ,this.teacherAge,this.yearsofServices ));
       }
    }

当然如果我这样写的话:

   public struct  StructTeacher
    {
       public string teacherName{get;set ;}
       public int teacherAge { get; set; }
       public int yearsofServices { get; set; }
       public StructTeacher(string teachername, int teacherage, int yearsofservices)
       {
           this .teacherName=teachername;
           this .teacherAge=teacherage;
           this.yearsofServices =yearsofservices ;
       }
       public void sayHi(string teachername, int teacherage, int yearsofservices)
       {
           MessageBox.Show(string .Format("大家好,我是{0},今年{1}岁,我已经在教育战线上奋斗了{2}年了",this.teacherName ,this.teacherAge,this.yearsofServices ));
       }
    }

那么就会出现如下报错:

所以,在使用结构的时候千万要记住,结构中的属性字段是不可以赋值的。

抱歉!评论已关闭.