using System; using System.Text.RegularExpressions; namespace FlexFramework.Excel { /// /// A range of /// public struct Range : IEquatable { #region Equality members public bool Equals(Range other) { return From.Equals(other.From) && To.Equals(other.To); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is Range && Equals((Range)obj); } public override int GetHashCode() { unchecked { return (From.GetHashCode() * 397) ^ To.GetHashCode(); } } #endregion /// /// Range from /// public Address From { get; private set; } /// /// Range to /// public Address To { get; private set; } /// /// Initializes a new instance of the Range class /// /// Range from /// Range to public Range(Address @from, Address to) { if (@from >= to) throw new ArgumentException("begin address is larger than or equal to end address"); From = @from; To = to; } /// /// Initializes a new instance of the Range class /// /// Range expression; e.g. A1:C12 public Range(string range) { var args = range.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (args.Length != 2) throw new FormatException(); var @from = new Address(args[0]); var to = new Address(args[1]); if (@from >= to) throw new ArgumentException("begin address is larger than or equal to end address"); From = @from; To = @to; } /// /// Check if this range contains target address /// /// Address to check /// True if contains public bool Contains(Address address) { return address >= From && address <= To; } /// /// Check if this range contains target range /// /// Range to check /// True if contains public bool Contains(Range range) { return range.From >= From && range.To <= To; } public override string ToString() { return string.Format("{0}:{1}", From, To); } public static bool operator ==(Range range, Range other) { return range.From == other.From && range.To == other.To; } public static bool operator !=(Range range, Range other) { return range.From != other.From || range.To != other.To; } /// /// Check if the given range is valid /// /// /// True if valid public static bool IsValid(string range) { return Regex.IsMatch(range, "^[A-Z]+\\d+:[A-Z]+\\d+$"); } } }