zoukankan      html  css  js  c++  java
  • 属性中限定输入值并抛出异常

    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 + "
    Val: " + 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("
    Attempting 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:
    "{0}"", e.Message);
                }
             }
             Console.WriteLine("
    Outputting myObj.ToString()…...");
             Console.WriteLine(myObj.ToString());
             Console.WriteLine("myObj.ToString() Output.");
             Console.ReadKey();
          }
       }
    }
    View Code

     

  • 相关阅读:
    Android动画 interpolator的用法
    ListView的addAll方法
    界面切换动画
    ListView的setSelectionFromTop()方法与setSelection()方法的联系
    new总结
    linux中进程控制
    linux设备模型
    如何将驱动加入内核
    linux缓冲的概念fopen /open,read/write和fread/fwrite区别
    点云的滤波
  • 原文地址:https://www.cnblogs.com/swtool/p/5522450.html
Copyright © 2011-2022 走看看