您的位置:首页 > 其它

XCodeFactory疑问--生成的数据对象类中的const字段有什么用啊?

2005-09-15 11:21 357 查看
比如在XCodeFactory3.0完全攻略--简单示例中的生成的Student代码中有如下const字段:

#region FieldName ,用于强化静态检查
public const string _ID = "ID" ;
public const string _Name = "Name" ;
public const string _Age = "Age" ;
public const string _ClassGrade = "ClassGrade" ;
public const string _MentorID = "MentorID" ;
public const string _Description = "Description" ;
#endregion
正如注释说的那样,这些字段的存在是为了强化静态检查。IDBAccesser接口和DataEntrance中的很多方法都要求传入where字句或数据库表的字段名称,比如,获取编号为1001的学生的年龄,使用DataEntrance是这样做的:

int age = (int)DataEntrance.GetFieldValue(typeof(Student) ,"1001" ,"Age") ;
如果哪天,Age字段改变了名字或者被删除了,上面的代码依然能编译通过,但在运行时就会抛出异常。我们需要一种方法来在编译时期就检查出这种错误。于是我想到了使用const成员来保存每个字段的名称,它们是一一对应的关系,使用const成员后,上面的代码变成这样:

int age = (int)DataEntrance.GetFieldValue(typeof(Student) ,"1001" ,Student._Age) ;
使用这样的方式,如果Age字段改变了名字或者被删除了,Student便没有了_Age这个const字段,所以编译就会发生错误,这样就把运行时发生的错误提前到了编译期,这对系统的稳定是大大有利的!

所以,在需要where字句的地方,我们经常这样用const字段:

string whereStr = string.Format("where {0} >'25' '" ,Student._Age) ;
Student[] students = (Student[])DataEntrance.GetObjects(typeof(Student) ,whereStr) ;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐