Net面向对象程序设计-15-实现属性以访问字段.ppt

上传人:sh****n 文档编号:6388032 上传时间:2020-02-24 格式:PPT 页数:31 大小:275.05KB
返回 下载 相关 举报
Net面向对象程序设计-15-实现属性以访问字段.ppt_第1页
第1页 / 共31页
Net面向对象程序设计-15-实现属性以访问字段.ppt_第2页
第2页 / 共31页
Net面向对象程序设计-15-实现属性以访问字段.ppt_第3页
第3页 / 共31页
点击查看更多>>
资源描述
NET面向对象程序设计第15章实现属性以访问字段 本章简介 使用属性封装逻辑字段声明getaccessor声明setaccessor创建声明了属性的接口使用结构和类实现含有属性的接口根据字段定义自动生成属性用属性来初始化对象 15 1使用方法来实现封装 以下结构用于将屏幕上的一个位置表示成一个 X Y 坐标对假定x坐标的取值范围是0 1280 y的取值范围是0 1024 privatestaticintrangeCheckedX intx if x1280 thrownewArgumentOutOfRangeException X returnx privatestaticintrangeCheckedY inty if y1024 thrownewArgumentOutOfRangeException Y returny structScreenPosition publicintX publicintY publicScreenPosition intx inty this X rangeCheckedX x this Y rangeCheckedY y 问题 违反了封装的原则 没有将其数据保持private状态虽然ScreenPosition构造器会对它的参数进行范围检查 但在创建好一个对象后 就可以随便访问public字段ScreenPositionorigin newScreenPosition 0 0 intxpos origin X origin Y 100 oops 解决该问题的方法 将字段设为private 并添加一个取值 getraccessor 方法和一个赋值 setaccessor 方法 以便分别读取和写入每个private字段的值然后 赋值方法就可以对新的字段值执行范围检查缺点 它使用的是不太方便的 基于方法的语法intxpos origin GetX origin SetX xpos 10 structScreenPosition publicintGetX returnthis x publicvoidSetX intnewX this x rangeCheckedX newX privatestaticintrangeCheckedX intx privatestaticintrangeCheckedY inty privateintx y 15 2什么是属性 属性 property 是字段和方法的一个交集 它看起来像是一个字段 行为上又像一个方法访问一个属性所用的语法和访问一个字段的语法是相同的编译器会将这种字段风格的语法自动转换成对特定accessor方法的调用 语法 AccessModifierTypepropertyName get readaccessorcode set writeaccessorcode structScreenPosition privateintx y publicScreenPosition intX intY this x rangeCheckedX X this y rangeCheckedY Y publicintX get returnthis x set this x rangeCheckedX value publicintY get returnthis y set this y rangeCheckedY value privatestaticintrangeCheckedX intx privatestaticintrangeCheckedY inty 注意 所有setaccessor都用一个隐藏的 内建的参数来传递要写入的数据public字段和属性大写 private的字段和属性小写 属性为访问对象内的实例变量及访问另一个对象中的实例变量提供了一致性的语法 属性与等价的存取器方法执行速度同样快 当属性的get语句块和set语句块编译成MSIL时 它们都转换成方法 在MSIL中 get语句块由一个名字为get 的方法表示 set同样 8 15 2 1使用属性 从ScreenPosition结构的X和Y属性中取值 ScreenPositionorigin newScreenPosition 0 0 intxpos origin X callsorigin X getintypos origin Y callsorigin Y get对属性进行赋值 编译器自动将字段风格的代码转换成对该属性的setaccessor的调用origin X 40 callsorigin X set withvaluesetto40origin Y 100 callsorigin Y Set withvaluesetto100可以通过static关键字声明静态属性 访问static属性时 要附加类或者结构的名称而不是其实例的名称作为前缀 15 2 2只读属性 可以声明只包含一个getaccessor的属性 即声明了一个只读属性X属性不包含setaccessor 所以 如下操作错误origin X 140 compile timeerror 示例 structScreenPosition publicintX get returnthis x 15 2 3只写属性 也可以声明只包含一个setaccessor的属性 即声明了一个只写属性X属性不包含getaccessor 所以 如下操作错误Console WriteLine origin X 编译器errororigin X 200 OKorigin X 10 编译器error 示例 structScreenPosition publicintX set this x rangeCheckedX value 只写属性适用于对密码这样的属性进行保护 15 2 4属性的可访问性 可访问性是在声明属性时指定的 但是 在属性的声明中 可以为get和set单独指定可访问性 structScreenPosition publicintX get returnthis x privateset this x rangeCheckedX value publicintY get returnthis y privateset this y rangeCheckedY value privateintx y 注意 定义时 只能改变一个accessor的可访问性accessor的访问修饰符所指定的可访问性在限制程度上必须大于属性的可访问性警告 习惯上 为属性和private字段赋予几乎完全相同的名称 只是首字母大小写有别但是 要小心使用 classEmployee privateintemployeeID publicintEmployeeID get returnthis EmployeeID set this EmployeeID value 15 3理解属性的局限性 属性在外观 行为和感觉上都类似于字段 但它们本质上是方法 并不是真正的字段属性的限制 只有在一个结构或类初始化好之后 才能通过这个结构或类的属性来进行赋值ScreenPositionlocation location X 40 compile timeerror locationnotassigned所以 定义结构和类时 一开始就应该使用属性 而不是先用字段 后来又变成属性 字段变成属性后 以前使用了这个类或结构的代码就可能无法正常工作 不能将属性作为一个ref或者out参数值传给一个方法 但可以将一个可写的字段作为ref或out参数值传递 这是因为属性并不真正指向一个内存位置 它代表的是一个方法在一个属性中 最多只能包含一个getaccessor和一个setaccessor 属性不能包含其他方法 字段或属性getaccessor和setaccessor不能获取任何参数 要赋的值会通过内建的 隐藏的value变量 自动传给setaccessor不能声明const属性 合理使用属性 classBankAccount publicmoneyBalance get set privatemoneybalance classBankAccount publicmoneyBalance get publicvoidDeposit moneyamount publicboolWithdraw moneyamount privatemoneybalance 15 4在接口中声明属性 除了可在接口中声明方法之外 还可以定义属性interfaceIScreenPosition intX get set intY get set 实现该接口的任何类或结构都必须实现X和Y属性 并在属性中定义get和set structScreenPosition IScreenPosition publicintX get set publicintY get set 在类中实现接口属性时 可以将属性的实现声明为virtual 以允许未来派生的类重写这些实现例如 classScreenPosition IScreenPosition publicvirtualintX get set publicvirtualintY get set 还可以选择使用显式接口实现语法来实现一个属性 属性的显式实现是非公共和非虚的 因而不能被重写 structScreenPosition IScreenPosition intIScreenPosition X get set intIScreenPosition Y get set privateintx y 课本276页练习 15 5生成自动属性 属性的两个主要优势 与应用程序的兼容性与接口的兼容性 如果要实现一个接口 而且接口将一个数据项定义成属性 就必须实现这个属性 使之与接口中的规范相符C 编译器能够自动为属性生成代码classCircle publicintRadius get set 自动生成的属性不可以是只读或者只写的 classCircle privateint radius publicintRadius get returnthis radius set this radius value 15 6使用属性来初始化对象 publicclassTriangle privateintside1Length privateintside2Length privateintside3Length publicTriangle this side1Length this side2Length this side3Length 10 publicTriangle intlength1 this side1Length length1 this side2Length this side3Length 10 publicTriangle intlength1 intlength2 this side1Length length1 this side2Length length2 this side3Length 10 publicTriangle intlength1 intlength2 intlength3 this side1Length length1 this side2Length length2 this side3Length length3 可以使用命名参数 然而更好和更透明的方式是将私有变量初始化为它们的默认值并定义属性 publicclassTriangle privateintside1Length 10 privateintside2Length 10 privateintside3Length 10 publicintSide1Length set this side1Length value publicintSide2Length set this side2Length value publicintSide3Length set this side3Length value Triangletri1 newTriangle Side3Length 15 Triangletri2 newTriangle Side1Length 15 Side3Length 20 Triangletri3 newTriangle Side2Length 12 Side3Length 17 Triangletri4 newTriangle Side1Length 9 Side2Length 12 Side3Length 15 24 应用 使用属性实现延迟初始化和惰性更新 当一个变量很少使用而且它的初始化即浪费时间又浪费资源时 可使用延迟初始化技术 惰性更新 lazyupdate 25 实例分析 为农产品商人编写程序要求 在合理的精度范围内预测不同地区来年的产量和质量 相关地区10天内降水量预测是核心参数每次降水量预测要占用一定的cpu时间每次计算从零开始 每20秒提供一个更新更准确的预报不同的作物有不同的种植季节 所以用户在每年的特定时间只需预报其中的几种 而且每次预报只限于几个地区 26 程序源代码 CropForecaster cs 01 usingSystem 02 usingSystem Timers 03 04 classWeatherForecaster05 06 publicstaticdoubleCalculateRainfallDay10RegionA 07 08 Simulatedcomplexcalculationstakes5000milliseconds09 System Threading Thread Sleep 5000 10 Randomrandomizer newRandom 11 return double randomizer Next 40 100 12 13 14 27 15 classCropForecaster16 17 privatedoublerainfallDay10RegionA 18 privateboolrainfallDay10RegionANeedUpdate true 19 20 publicCropForecaster 21 22 TimeraTimer newTimer 23 aTimer Elapsed newElapsedEventHandler OnTimedEvent 24 aTimer Interval 20000 25 aTimer Enabled true 26 27 28 publicdoubleRainfallDay10RegionA29 30 get31 32 if rainfallDay10RegionANeedUpdate 33 34 rainfallDay10RegionA WeatherForecaster CalculateRainfallDay10RegionA 35 rainfallDay10RegionANeedUpdate false 36 returnrainfallDay10RegionA 37 38 else39 40 returnrainfallDay10RegionA 41 42 43 28 45 privatedoubleComplexResultA 46 47 ArbitrarycalculationinvolvinglotsofcallstorainfallDay10RegionA48 return RainfallDay10RegionA 2 RainfallDay10RegionA 3 49 RainfallDay10RegionA 4 50 51 52 privatedoubleComplexResultB 53 54 ArbitrarycalculationinvolvingevenmorecallstorainfallDay10RegionA55 return RainfallDay10RegionA 10 100 RainfallDay10RegionA 100 56 57 58 publicdoubleWheatCropSizeInTonsInRegionA 59 60 Morearbitrarycalculationsreturninganicebigresult61 Console WriteLine Commencingforecastcalculations Pleasewait 62 return ComplexResultA 2 ComplexResultB 4 63 ComplexResultA 100000 64 65 66 publicvoidOnTimedEvent objectsource ElapsedEventArgse 67 68 Thismethodiscurrentlycalledautomaticallyevery20seconds69 Console WriteLine n nNewUpdateNeeded nPerformanotherforecast 70 rainfallDay10RegionANeedUpdate true 71 72 29 74 classForecastTester75 76 publicstaticvoidMain 77 78 stringanswer 79 CropForecastermyForecaster newCropForecaster 80 81 Console Write Wouldyouliketoperformacropforecast Y esN o 82 answer Console ReadLine ToUpper 83 while answer N 84 85 Console WriteLine Wheatcropsizeintons 0 N2 86 myForecaster WheatCropSizeInTonsInRegionA 87 Console Write Wouldyouliketoperformanothercropforecast Y esN o 88 answer Console ReadLine ToUpper 89 90 91 30 运行结果 Wouldyouliketoperformacropforecast Y esN oYCommencingforecastcalculations Pleasewait Wheatcropsizeintons 10 389 500 00Wouldyouliketoperformanothercropforecast Y esN oYCommencingforecastcalculations Pleasewait Wheatcropsizeintons 10 389 500 00Wouldyouliketoperformanothercropforecast Y esN oYCommencingforecastcalculations Pleasewait Wheatcropsizeintons 10 389 500 00Wouldyouliketoperformanothercropforecast Y esN oNewUpdateNeededPerformanotherforecast YCommencingforecastcalculations Pleasewait Wheatcropsizeintons 13 694 500 00Wouldyouliketoperformanothercropforecast Y esN oN 课本281页练习
展开阅读全文
相关资源
相关搜索

当前位置:首页 > 图纸专区 > 课件教案


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!