测试(VS自带框架):

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;/// <summary>
///This is a test class for YearMonthTest and is intended
///to contain all YearMonthTest Unit Tests
///</summary>
[TestClass()]
public class YearMonthTest
{/// <summary>///A test for YearMonth Constructor///</summary>[TestMethod()]public void YearMonthConstructorTest(){var date = new DateTime(2000, 1, 1);var target = new YearMonth(date);Assert.AreEqual(2000, target.Year);Assert.AreEqual(1, target.Month);}/// <summary>///A test for YearMonth Constructor///</summary>[TestMethod()]public void YearMonthConstructorTest1(){YearMonth target = new YearMonth(2010, 4);Assert.AreEqual(2010, target.Year);Assert.AreEqual(4, target.Month);}/// <summary>///A test for GetDate///</summary>[TestMethod()]public void GetDateTest(){var target = new YearMonth(2010, 5);var expected = new DateTime(2010, 5, 3);var actual = target.GetDate(3);Assert.AreEqual(expected, actual);}[TestMethod]public void GetDateThrows(){Assert.IsTrue(Throws(typeof(ArgumentOutOfRangeException), () => new YearMonth(2012, 12).GetDate(32)));}/// <summary>///A test for ToString///</summary>[TestMethod()]public void ToStringTest(){var target = new YearMonth(2008, 3);Assert.AreEqual("200803", target.ToString());}/// <summary>///A test for IsValid///</summary>[TestMethod()]public void IsValidTest(){Assert.IsTrue(new YearMonth(2008, 12).IsValid);Assert.IsFalse(new YearMonth(2010, 13).IsValid);Assert.IsFalse(new YearMonth(2010, 0).IsValid);Assert.IsFalse(new YearMonth(2010, -3).IsValid);Assert.IsFalse(new YearMonth(0, 3).IsValid);Assert.IsFalse(new YearMonth(-2, 3).IsValid);Assert.IsTrue(new YearMonth(9999, 12).IsValid);Assert.IsFalse(new YearMonth(10000, 1).IsValid);Assert.IsFalse(new YearMonth(-2, -3).IsValid);}/// <summary>///A test for Equals///</summary>[TestMethod()]public void EqualsTest(){var target = new YearMonth(2010, 4);Assert.IsTrue(target.Equals(new YearMonth(2010, 4)));Assert.IsFalse(target.Equals(new YearMonth(2010, 3)));Assert.IsFalse(target.Equals(string.Empty));}/// <summary>///A test for TryParse///</summary>[TestMethod()]public void TryParseTest(){YearMonth result;var success = YearMonth.TryParse("201012", out result);Assert.IsTrue(success);Assert.AreEqual(new YearMonth(2010, 12), result);success = YearMonth.TryParse("", out result);Assert.IsFalse(success);Assert.AreEqual(result, null);}/// <summary>///A test for Parse///</summary>[TestMethod()]public void ParseTest(){Assert.AreEqual(new YearMonth(2008, 12), YearMonth.Parse("200812"));}[TestMethod]public void ParseThrows(){Assert.IsTrue(Throws(typeof(ArgumentNullException), () => YearMonth.Parse(null)));Assert.IsTrue(Throws(typeof(ArgumentException), () => YearMonth.Parse("")));Assert.IsTrue(Throws(typeof(ArgumentException), () => YearMonth.Parse("aaaaaa")));Assert.IsTrue(Throws(typeof(ArgumentException), () => YearMonth.Parse("20121221")));}/// <summary>///A test for AddYears///</summary>[TestMethod()]public void AddYearsTest(){Assert.AreEqual(new YearMonth(2011, 11), new YearMonth(2008, 11).AddYears(3));Assert.AreEqual(new YearMonth(2011, 11), new YearMonth(2011, 11).AddYears(0));Assert.AreEqual(new YearMonth(2011, 11), new YearMonth(2012, 11).AddYears(-1));}/// <summary>///A test for AddMonths///</summary>[TestMethod()]public void AddMonthsTest(){Assert.AreEqual(new YearMonth(2010, 4), new YearMonth(2010, 3).AddMonths(1));Assert.AreEqual(new YearMonth(2010, 4), new YearMonth(2010, 4).AddMonths(0));Assert.AreEqual(new YearMonth(2010, 4), new YearMonth(2010, 8).AddMonths(-4));Assert.AreEqual(new YearMonth(2010, 1), new YearMonth(2009, 11).AddMonths(2));Assert.AreEqual(new YearMonth(2009, 11), new YearMonth(2010, 1).AddMonths(-2));Assert.AreEqual(new YearMonth(2009, 12), new YearMonth(2010, 1).AddMonths(-1));Assert.AreEqual(new YearMonth(2010, 1), new YearMonth(2009, 12).AddMonths(1));}static bool Throws(Type exceptionType, Action action){try{action();}catch (Exception ex){if (ex.GetType() == exceptionType || ex.GetType().IsSubclassOf(exceptionType))return true;throw;}return false;}
}

代码:

using System;
using System.Linq;/// <summary>
/// 代表一个年份中的某个指定月份. 如:2008年10月.
/// </summary>
public sealed class YearMonth
{private readonly int _year;private readonly int _month;/// <summary>/// 用指定的年份和月份构造一个 YearMonth 对象./// </summary>/// <param name="year">年号,如2012.</param>/// <param name="month">月份,1代表1月,12代表12月.</param>public YearMonth(int year, int month){_year = year;_month = month;}/// <summary>/// 根据指定日期所在的月份构造一个 YearMonth 对象./// </summary>/// <param name="date">指定的日期.它的年份和月份部分会作为构造的YearMonth的值使用.</param>public YearMonth(DateTime date){_year = date.Year;_month = date.Month;}public int Year{get { return _year; }}public int Month{get { return _month; }}/// <summary>/// 是否是有效的值.无效的值可能是年份小于1, 或年份大于9999, 或月份小于1, 或月份大于12./// </summary>public bool IsValid{get{return 0 < Year && Year < 10000&& 0 < Month && Month < 13;}}/// <summary>/// 获取代表该月指定日期的 DateTime 对象/// </summary>/// <param name="day">日期,范围1到31.</param>/// <exception cref="ArgumentOutOfRangeException">day大于本月的天数.</exception>public DateTime GetDate(int day){return new DateTime(Year, Month, day);}/// <summary>/// 返回一个新YearMonth对象,其值为当前对象的值加上指定个年份/// </summary>/// <param name="value">要在当前年月上增加多少年</param>public YearMonth AddYears(int value){return new YearMonth(Year + value, Month);}/// <summary>/// 返回一个新YearMonth对象,其值为当前对象的值加上指定个月份/// </summary>/// <param name="value">要在当前年月上增加多少个月</param>public YearMonth AddMonths(int value){var totalMonths = Year * 12 + Month + value;var year = totalMonths / 12;var month = totalMonths % 12;if (month == 0){month = 12;year--;}return new YearMonth(year, month);}/// <summary>/// 返回数字代表的年月份值,共6位数字,前4位代表年份,后两位代表月份,如:200805/// </summary>public override string ToString(){return "{0:D4}{1:D2}".FormatWith(Year, Month);}/// <summary>/// 判断一个是否与当前对象代表相同的值的YearMonth对象./// </summary>public override bool Equals(object obj){return Equals(obj as YearMonth);}/// <summary>///判断另一个YearMonth对象是否与当前对象代表相同的值. /// </summary>public bool Equals(YearMonth rhs){if (ReferenceEquals(null, rhs))return false;if (ReferenceEquals(this, rhs))return true;return _year == rhs._year &&_month == rhs._month;}public override int GetHashCode(){unchecked{return (_year * 397) ^ _month;}}public static bool operator ==(YearMonth lhs, YearMonth rhs){return Object.Equals(lhs, rhs);}public static bool operator !=(YearMonth lhs, YearMonth rhs){return !(lhs == rhs);}public static bool TryParse(string s, out YearMonth result){try{result = Parse(s);return true;}catch (ArgumentException){result = null;return false;}}/// <summary>/// 通过解析字符串构造一个YearMonth对象./// </summary>/// <param name="s">要解析的字符串.</param>/// <exception cref="ArgumentNullException">s为null.</exception>/// <exception cref="ArgumentException">s包含非数字字符,或s的长度不为6.</exception>public static YearMonth Parse(string s){if (s == null)throw new ArgumentNullException("s");if (s.Length != 6 || s.Any(x => x < '0' || x > '9'))throw new ArgumentException("s应该是6位数字.");var year = int.Parse(s.Substring(0, 4));var month = int.Parse(s.Substring(4));return new YearMonth(year, month);}
}

辅助方法:

public static class StringExtensions
{public static string FormatWith(this string format, object arg0){return string.Format(format, arg0);}public static string FormatWith(this string format, object arg0, object arg1){return string.Format(format, arg0, arg1);}public static string FormatWith(this string format, object arg0, object arg1, object arg2){return string.Format(format, arg0, arg1, arg2);}
}

转载于:https://www.cnblogs.com/deerchao/archive/2010/04/21/1717228.html

一个代表年月的类YearMonth相关推荐

  1. java写一个外网访问的接口_【JAVA基础】一个案例搞懂类、对象、重载、封装、继承、多态、覆盖、抽象和接口概念及区别(中篇)...

    0 前言 初学JAVA时,总会对一些概念一知半解,相互混淆,不明其设计的用意,如类.对象.重载.封装.继承.多态.覆盖.抽象类.接口概念.为便于理解和巩固,本文将基于一个案例及其变形,展现各个概念的定 ...

  2. python自己做个定时器_技术图文:如何利用 Python 做一个简单的定时器类?

    原标题:技术图文:如何利用 Python 做一个简单的定时器类? 背景 今天在B站上看有关 Python 最火的一个教学视频 -- "零基础入门学习 Python",这也是我们 P ...

  3. 构建一个你自己的类微信系统 -- 可扩展通信系统实践

    ##前言 正如你们所知的那样,微信是一个非常成功的在线服务系统,由几万台服务器组成的系统为几亿人提供着稳定的业务服务.可惜作为一个普通的工程师基本上不可能有整体设计这样一个系统的机会,即使加入xx 也 ...

  4. 请定义一个交通工具(Vehicle)的类,其中有: 属性:速度(speed),体积(size)等等 方法:移动(move()),设置速度(setSpeed(int speed)),加速speedUp

    前言 请定义一个交通工具(Vehicle)的类,其中有: 属性:速度(speed),体积(size)等等  方法:移动(move()),设置速度(setSpeed(int speed)),加速spee ...

  5. 以家联家网站为代表的F2F-SNS类网站类

    以家联家网站为代表的F2F-SNS类网站类 或将成为下一个网络热点 "为什么要做家联家网站?"当我向两位美女网站负责人CHRISTINE和ADINO询问做这个网站的缘起时,她们告诉 ...

  6. c++设计一个不能被继承的类

    摘要:使用友元.私有构造函数.虚继承等方式可以使一个类不能被继承,可是为什么必须是虚继承?背后的原理又是什么? 用C++实现一个不能被继承的类(例1) 1 #include <iostream& ...

  7. 分享一个异步发送邮件的类

    首先要定义一个邮件信息的基类,如下所示: /// <summary>     /// Base message class used for emails     /// </sum ...

  8. 定义一个Teacher(教师)类,和一个Student(学生)类

    定义一个Teacher(教师)类,和一个Student(学生)类,二者有一部分数据成员是相同的,例如num(号码),name(姓名),sex(性别).编写程序,将一个Student对象 转换为Teac ...

  9. python简单代码演示效果-演示python如何创建和使用一个简单的元类的代码

    在做工程闲暇时间,将做工程过程比较重要的一些内容备份一下,如下内容段是关于演示python如何创建和使用一个简单的元类的内容,应该能对小伙伴们也有用途. #!/usr/bin/env python # ...

最新文章

  1. 如何设计电桥传感器驱动电路?
  2. vs2005什么时候能出正式版
  3. 2w字 + 40张图带你参透并发编程!
  4. 线粒体|GetOrganelle组装软件
  5. 扩展KMP --- HDU 3613 Best Reward
  6. mysql -u -p -d_mysqld_exporter监控mysql
  7. ResNeXt 之 输入数据预处理代码详解
  8. WPF不同线程之间的控件的访问
  9. 使用K-S检验一个数列是否服从正态分布、两个数列是否服从相同的分布(转载+自己笔记)
  10. python中文件描述符_Python中的描述符
  11. cookie记录了服务器相关的信息,使用cookie记录信息(精选).ppt
  12. 产品经理必看:终于有人把数据指标讲明白了
  13. python编程语言-Python成为2018年度编程语言,遥遥领先于其他语言
  14. 剪映专业版 for Mac(全能好用的视频编辑工具)v1.0.11中文版
  15. Java集合里面的值唯一_java 判断集合元素唯一的原理
  16. 网页资源嗅探java_网页资源嗅探器下载_ESFSoft URL Sniffer(嗅探网页音频视频文件) 1.1 英文版_极速下载站...
  17. 行业分析常用到的21个网站
  18. 扫雷——Windows上的经典小游戏
  19. 【损失函数】生成任务感知损失小结
  20. 图像超分辨率:优化最近邻插值Super-Resolution by Predicting Offsets

热门文章

  1. WPF 4 动态覆盖图标(Dynamic Overlay Icon)
  2. 微信公众号 语音转文字api_微信重新上线的灰度测试功能:语音上滑转文字发送...
  3. java sftp 公开键设定_如何使用JSch SFTP库解析Java UnknownHostKey?
  4. php 模板继承原理,模板继承体会
  5. Golang 实现【链表反转】
  6. 06MySQL基本函数的使用
  7. 3-8Tensor的算术运算编程实例
  8. 数据可视化之MATPLOTLIB实战:PLT.POLAR()函数 绘制极线图 (转载)
  9. vs安装 c语言编译环境,Visual Studio Code安装与C/C++开发调试环境搭建
  10. LGBM使用贝叶斯调参