⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 enumex.cs

📁 Opennet 发送和接受程序,可用于移动存储设备的开发,请好好查看
💻 CS
📖 第 1 页 / 共 2 页
字号:
		#region Parse
		/// <summary>
		/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
		/// </summary>
		/// <param name="enumType">The <see cref="T:System.Type"/> of the enumeration.</param>
		/// <param name="value">A string containing the name or value to convert.</param>
		/// <returns>An object of type enumType whose value is represented by value.</returns>
		public static object Parse(System.Type enumType, string value)
		{
			//do case sensitive parse
			return Parse(enumType, value, false);
		}
		/// <summary>
		/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
		/// A parameter specifies whether the operation is case-sensitive.
		/// </summary>
		/// <param name="enumType">The <see cref="T:System.Type"/> of the enumeration.</param>
		/// <param name="value">A string containing the name or value to convert.</param>
		/// <param name="ignoreCase">If true, ignore case; otherwise, regard case.</param>
		/// <returns>An object of type enumType whose value is represented by value.</returns>
		/// <exception cref="System.ArgumentException">enumType is not an <see cref="T:System.Enum"/>.
		///  -or-  value is either an empty string ("") or only contains white space.
		///  -or-  value is a name, but not one of the named constants defined for the enumeration.</exception>
		///  <seealso cref="M:System.Enum.Parse(System.Type,System.String,System.Boolean)">System.Enum.Parse Method</seealso>
		public static object Parse(System.Type enumType, string value, bool ignoreCase)
		{
#if NETCF2
			//use intrinsic functionality in v2
			return Enum.Parse(enumType,value,ignoreCase);
#else
			//throw an exception on null value
			if(value.TrimEnd(' ')=="")
			{
				throw new ArgumentException("value is either an empty string (\"\") or only contains white space.");
			}
			else
			{
				//type must be a derivative of enum
				if(enumType.BaseType==Type.GetType("System.Enum"))
				{
					//remove all spaces
					string[] memberNames = value.Replace(" ","").Split(',');
					
					//collect the results
					//we are cheating and using a long regardless of the underlying type of the enum
					//this is so we can use ordinary operators to add up each value
					//I suspect there is a more efficient way of doing this - I will update the code if there is
					long returnVal = 0;

					//for each of the members, add numerical value to returnVal
					foreach(string thisMember in memberNames)
					{
						//skip this string segment if blank
						if(thisMember!="")
						{
							try
							{
								if(ignoreCase)
								{
									returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null),returnVal.GetType(), null);
								}
								else
								{
									returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static).GetValue(null),returnVal.GetType(), null);
								}
							}
							catch
							{
								try
								{
									//try getting the numeric value supplied and converting it
									returnVal += (long)Convert.ChangeType(System.Enum.ToObject(enumType, Convert.ChangeType(thisMember, System.Enum.GetUnderlyingType(enumType), null)),typeof(long),null);
								}
								catch
								{
									throw new ArgumentException("value is a name, but not one of the named constants defined for the enumeration.");
								}
								//
							}
						}
					}


					//return the total converted back to the correct enum type
					return System.Enum.ToObject(enumType, returnVal);
				}
				else
				{
					//the type supplied does not derive from enum
					throw new ArgumentException("enumType parameter is not an System.Enum");
				}
			}
#endif
		}
		#endregion

		#region To Object
		/// <summary>
		/// Returns an instance of the specified enumeration set to the specified value.
		/// <para><b>New in v1.1</b></para>
		/// </summary>
		/// <param name="enumType">An enumeration.</param>
		/// <param name="value">The value.</param>
		/// <returns>An enumeration object whose value is <paramref>value</paramref>.</returns>
		/// <seealso cref="System.Enum.ToObject(System.Type, System.Object)">System.Enum.ToObject Method</seealso>
		public static object ToObject(System.Type enumType, object value)
		{
			return System.Enum.ToObject(enumType, value);
		}
		#endregion

		#region Format
		private static string InternalFormat(Type enumType, object value)
		{
			if (enumType.IsDefined(typeof(FlagsAttribute), false))
				return InternalFlagsFormat(enumType, value);

			string t = GetName(enumType, value);
			if (t == null) 
				return value.ToString();
			
			return t;
		}

		private static string InternalFlagsFormat(Type enumType, object value)
		{
			string t = GetName(enumType, value);
			if (t == null) 
				return value.ToString();

			return t;
		}

		private static string InternalValuesFormat(Type enumType, object value, bool showValues)
		{
			string [] names = null;
			if (!showValues) names = GetNames(enumType);
			ulong v = Convert.ToUInt64(value); 
			Enum [] e = GetValues(enumType);
			ArrayList al = new ArrayList();
			for(int i = 0; i < e.Length; i++)
			{
				ulong ev = (ulong)Convert.ChangeType(e[i], typeof(ulong), null);
				if (i == 0 && ev == 0) continue;
				if ((v & ev) == ev)
				{
					v -= ev;
					if (showValues)
						al.Add(ev.ToString());
					else
						al.Add(names[i]);
				}
			}

			if (v != 0)
				return value.ToString();


			string [] t = (string [])al.ToArray(typeof(string)); 
			return string.Join(", ", t);
		}

		/// <summary>
		/// Converts the specified value of a specified enumerated type to its equivalent string representation according to the specified format. 
		/// </summary>
		/// <remarks>
		/// The valid format values are: 
		/// "G" or "g" - If value is equal to a named enumerated constant, the name of that constant is returned; otherwise, the decimal equivalent of value is returned.
		/// For example, suppose the only enumerated constant is named, Red, and its value is 1. If value is specified as 1, then this format returns "Red". However, if value is specified as 2, this format returns "2".
		/// "X" or "x" - Represents value in hexadecimal without a leading "0x". 
		/// "D" or "d" - Represents value in decimal form.
		/// "F" or "f" - Behaves identically to "G" or "g", except the FlagsAttribute is not required to be present on the Enum declaration. 
		/// "V" or "v" - If value is equal to a named enumerated constant, the value of that constant is returned; otherwise, the decimal equivalent of value is returned.
		/// </remarks>
		/// <param name="enumType">The enumeration type of the value to convert.</param>
		/// <param name="value">The value to convert.</param>
		/// <param name="format">The output format to use.</param>
		/// <returns>A string representation of value.</returns>
		public static string Format(Type enumType, object value, string format)
		{
			if (enumType == null) throw new ArgumentNullException("enumType");
			if (value == null) throw new ArgumentNullException("value");
			if (format == null) throw new ArgumentNullException("format");
			if (!enumType.IsEnum) throw new ArgumentException("The argument enumType must be an System.Enum.");

			if (string.Compare(format, "G", true, CultureInfo.InvariantCulture) == 0)
				return InternalFormat(enumType, value);
			if (string.Compare(format, "F", true, CultureInfo.InvariantCulture) == 0)
				return InternalValuesFormat(enumType, value, false);
			if (string.Compare(format, "V", true, CultureInfo.InvariantCulture) == 0)
				return InternalValuesFormat(enumType, value, true);
			if (string.Compare(format, "X", true, CultureInfo.InvariantCulture) == 0)
				return InternalFormattedHexString(value);
			if (string.Compare(format, "D", true, CultureInfo.InvariantCulture) == 0)
				return Convert.ToUInt64(value).ToString(); 

			throw new FormatException("Invalid format.");
		}

		private static string InternalFormattedHexString(object value)
		{
			switch (Convert.GetTypeCode(value))
			{
				case TypeCode.SByte:
				{
					sbyte n = (sbyte) value;
					return n.ToString("X2", null);
				}
				case TypeCode.Byte:
				{
					byte n = (byte) value;
					return n.ToString("X2", null);
				}
				case TypeCode.Int16:
				{
					short n = (short) value;
					return n.ToString("X4", null);
				}
				case TypeCode.UInt16:
				{
					ushort n = (ushort) value;
					return n.ToString("X4", null);
				}
				case TypeCode.Int32:
				{
					int n = (int) value;
					return n.ToString("X8", null);
				}
				case TypeCode.UInt32:
				{
					uint n = (uint) value;
					return n.ToString("X8", null);
				}

			}

			throw new InvalidOperationException("Unknown enum type.");
		}
		#endregion
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -