/// <summary> /// 在已知对象的属性 (Property) 值集的情况下,使用指定的上下文创建与此 System.ComponentModel.TypeConverter 关联的类型的实例。 /// </summary> /// <param name="context">System.ComponentModel.ITypeDescriptorContext,提供格式上下文。</param> /// <param name="propertyValues">新属性 (Property) 值的 System.Collections.IDictionary。</param> /// <returns>一个 System.Object,表示给定的 System.Collections.IDictionary,或者如果无法创建该对象,则为 null。此方法始终返回 null。</returns> public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { if (propertyValues == null) { throw new ArgumentNullException("propertyValues"); } object alpha = propertyValues["A"]; object red = propertyValues["R"]; object green = propertyValues["G"]; object blue = propertyValues["B"]; if (((alpha == null) || (red == null) || (green == null) || (blue == null)) || (!(alpha is short) || !(red is short) || !(green is short) || !(blue is short))) { throw new ArgumentException("属性值为无效输入"); } return(ColorVector.FromArgb((int)(short)alpha, (int)(short)red, (int)(short)green, (int)(short)blue)); }
/// <summary> /// 使用指定的上下文和区域性信息将给定的对象转换为此转换器的类型。 /// </summary> /// <param name="context">System.ComponentModel.ITypeDescriptorContext,提供格式上下文。</param> /// <param name="culture">用作当前区域性的 System.Globalization.CultureInfo。</param> /// <param name="value">要转换的 System.Object。</param> /// <returns>表示转换的 value 的 System.Object。</returns> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //NULL string str = value as string; if (str == null) { return(base.ConvertFrom(context, culture, value)); } //空字符串 string trimStr = str.Trim(); if (trimStr.Length <= 0) { return(ColorVector.Empty); } //区域分隔符 if (culture == null) { culture = CultureInfo.CurrentCulture; } char ch = culture.TextInfo.ListSeparator[0]; //类型转换器 TypeConverter longConverter = TypeDescriptor.GetConverter(typeof(long)); TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); //不含分隔符 if (trimStr.IndexOf(ch) == -1) { if (((trimStr[0] == '#') && (trimStr.Length == 13 || trimStr.Length == 17)) || ((trimStr.StartsWith("0x") || trimStr.StartsWith("0X") || trimStr.StartsWith("&h") || trimStr.StartsWith("&H")) && (trimStr.Length == 14 || trimStr.Length == 18))) { return(ColorVector.FromArgb((long)longConverter.ConvertFromString(trimStr))); } } else//包含分隔符 { string[] strArray = trimStr.Split(new char[] { ch }); int[] numArray = new int[strArray.Length]; for (int i = 0; i < numArray.Length; i++) { numArray[i] = (int)intConverter.ConvertFromString(context, culture, strArray[i]); } switch (numArray.Length) { case 3: return(ColorVector.FromArgb(numArray[0], numArray[1], numArray[2])); case 4: return(ColorVector.FromArgb(numArray[0], numArray[1], numArray[2], numArray[3])); } } throw new ArgumentException("无效的颜色向量"); }