属性中限定输入值并抛出异常
2016-05-24 10:04
176 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ch10Ex01 { public class MyClass { public readonly string Name; private int intVal; public int Val { get { return intVal; } set { if (value >= 0 && value <= 10) intVal = value; else throw (new ArgumentOutOfRangeException("Val", value, "Val must be assigned a value between 0 and 10.")); } } public override string ToString() { return "Name: " + Name + "\nVal: " + Val; } private MyClass() : this("Default Name") { } public MyClass(string newName) { Name = newName; intVal = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ch10Ex01 { class Program { static void Main(string[] args) { Console.WriteLine("Creating object myObj…..."); MyClass myObj = new MyClass("My Object"); Console.WriteLine("myObj created."); for (int i = -1; i <= 0; i++) { try { Console.WriteLine("\nAttempting to assign {0} to myObj.Val…...", i); myObj.Val = i; Console.WriteLine("Value {0} assigned to myObj.Val.", myObj.Val); } catch (Exception e) { Console.WriteLine("Exception {0} thrown.", e.GetType().FullName); Console.WriteLine("Message:\n\"{0}\"", e.Message); } } Console.WriteLine("\nOutputting myObj.ToString()…..."); Console.WriteLine(myObj.ToString()); Console.WriteLine("myObj.ToString() Output."); Console.ReadKey(); } } }
View Code
相关文章推荐
- Java jar 指定main方法运行
- 详解Bootstrap网格系统
- PHPcms调去多图字段的方法
- Volley框架的基本解读(三)
- launchimage
- 解决“错误 D8016 “/ZI”和“/Gy-”命令行选项不兼容 ”问题
- js中onclick字符串传参问题
- 图片适应UIImageView
- matlab 对图像操作的函数概览
- 网络多线程O.3 队列组的用法
- iOS学习之—— UIPageViewController
- 安装 Ubuntu 下的 BeyondCompare
- lintcode ----删除排序链表中的重复元素
- Python网络爬虫Scrapy框架研究 以及 代理设置
- OC缓存 NSCache介绍
- 自定义缓存配置(非Web项目)
- PHPcms栏目页调取多图字段的方法
- 由浅入深探究 MySQL索引结构原理、性能分析与优化(一)
- js数组操作大全(pop,push,unshift,splice,shift方法)
- exec-timeout,session-timeout,timeout