Esempio n. 1
0
        public static string DisplayName(this Enum value, bool shortName = false, string seperator = ",")
        {
            Type type = value.GetType();

            if (Enum.IsDefined(type, value))
            {
                return(GetText(type, value, shortName));
            }

            if (type.IsDefined(typeof(FlagsAttribute), false))
            {
                Array         array = Enum.GetValues(type);
                List <string> list  = new List <string>(array.Length);
                object        zero  = Enum.ToObject(type, 0);
                foreach (Enum v in array)
                {
                    if (!zero.Equals(v) && value.HasFlag(v))
                    {
                        list.Add(GetText(type, v, shortName));
                    }
                }

                if (list.Count > 0)
                {
                    return(string.Join(seperator, list));
                }
            }

            return(value.ToString());
        }
Esempio n. 2
0
 public static IEnumerable <System.Enum> GetFlags(this System.Enum input)
 {
     foreach (System.Enum value in System.Enum.GetValues(input.GetType()))
     {
         if (input.HasFlag(value))
         {
             yield return(value);
         }
     }
 }
Esempio n. 3
0
 public static void FillWithFlagEnumeration(this SelectableListNodeList list, System.Enum enumerationValue)
 {
     list.Clear();
     foreach (System.Enum e in System.Enum.GetValues(enumerationValue.GetType()))
     {
         string baseName = e.ToString();
         bool isSelected = enumerationValue.HasFlag(e);
         list.Add(new SelectableListNode(baseName, e, isSelected));
     }
 }
Esempio n. 4
0
 /// <summary>
 /// enum 값에 포함된 각각의 flag를 추출하여 열거자 형태로 반환한다.
 /// </summary>
 public static IEnumerable <Enum> GetFlags(this Enum self)
 {
     foreach (Enum value in Enum.GetValues(self.GetType()))
     {
         if (self.HasFlag(value))
         {
             yield return(value);
         }
     }
 }
Esempio n. 5
0
        public static IEnumerable <System.Enum> EnumerateSettedUpFlags(this System.Enum flags)
        {
            foreach (var value in System.Enum.GetValues(flags.GetType()).Cast <System.Enum>())
            {
                var hasFlag = flags.HasFlag(value);

                if (hasFlag)
                {
                    yield return(value);
                }
            }
        }
        public static bool HasAllFlags([NotNull] this Enum value, [NotNull, ItemNotNull] params Enum[] flags)
        {
            foreach (var f in flags)
            {
                if (!value.HasFlag(f))
                {
                    return(false);
                }
            }

            return(true);
        }
        public static bool HasAnyFlag(this Enum value, params Enum[] flags)
        {
            foreach (var f in flags)
            {
                if (value.HasFlag(f))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 8
0
        /// <summary>
        /// Returns an array of set values in the given enum
        /// </summary>
        /// <remarks>
        /// This will return each set value if you have [Flags], or the single value if you don't
        /// </remarks>
        public static Array GetSetValues(Enum enumeration)
        {
            List<object> setValues = new List<object>();
            foreach (object possibleValue in Enum.GetValues(enumeration.GetType()))
            {
                if (enumeration.HasFlag((Enum)possibleValue))
                {
                    setValues.Add(possibleValue);
                }
            }

            return setValues.ToArray();
        }
Esempio n. 9
0
        /// <summary>
        /// 校验某个枚举组合值里是否包含特定的枚举
        /// </summary>
        /// <param name="combinedEnum">结合的枚举</param>
        /// <param name="verifyFlagsAttribute">是否要校验枚举是否包含Flags特性</param>
        /// <param name="enums">要判断的枚举值</param>
        /// <returns>是否包含指定的枚举值</returns>
        public static bool Contains(this System.Enum combinedEnum, bool verifyFlagsAttribute,
                                    params System.Enum[] enums)
        {
            if (combinedEnum == null)
            {
                throw new ArgumentNullException(nameof(combinedEnum));
            }

            if (enums == null || !enums.Any())
            {
                return(false);
            }

            if (!IsSameEnumDefine(enums))
            {
                //判断枚举类型是否一致,不一致则直接失败
                throw new ArgumentException($"param {nameof(enums)} inconsistent parameter type.");
            }

            var isFlag = IsDefineFlagsAttribute(enums.FirstOrDefault());

            if (verifyFlagsAttribute && !isFlag)
            {
                //如果需要校验Flags特性而枚举又没有定义该特性则直接失败
                throw new ArgumentException($"param {nameof(enums)} is not contains flags attribute.");
            }

            var combinedEnumInt = Convert.ToInt32(combinedEnum);

            foreach (var @enum in enums)
            {
                if (isFlag)
                {
                    if (!combinedEnum.HasFlag(@enum))
                    {
                        return(false);
                    }
                }
                else
                {
                    if ((combinedEnumInt & Convert.ToInt32(@enum)) == 0)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 10
0
 static int HasFlag(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         System.Enum obj  = (System.Enum)ToLua.CheckObject <System.Enum>(L, 1);
         System.Enum arg0 = (System.Enum)ToLua.CheckObject <System.Enum>(L, 2);
         bool        o    = obj.HasFlag(arg0);
         LuaDLL.lua_pushboolean(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Esempio n. 11
0
        public static IEnumerable <Enum> GetFlags(this Enum input, SortOrder order = SortOrder.Ascending)
        {
            Array values = Enum.GetValues(input.GetType());

            Array.Sort(values);
            if (order == SortOrder.Descending)
            {
                Array.Reverse(values);
            }

            foreach (Enum value in values)
            {
                if (input.HasFlag(value))
                {
                    yield return(value);
                }
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Method 'Remove' turns off this bit (does nothing if flag not present)
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="type">Enum type</param>
 /// <param name="value">value to remove</param>
 /// <returns></returns>
 public static T Remove <T>(this System.Enum type, T value)
 {
     try
     {
         if (type.HasFlag((Enum)(object)value))
         {
             return((T)(object)(((int)(object)type ^ (int)(object)value)));
         }
         return((T)(object)type);
     }
     catch (Exception ex)
     {
         throw new ArgumentException(
                   string.Format(
                       "Could not remove value from enumerated type '{0}'.",
                       typeof(T).Name
                       ), ex);
     }
 }
Esempio n. 13
0
        /// <summary>
        /// 获取 枚举名:枚举值 格式的 字符串
        /// </summary>
        /// <param name="emObj"></param>
        /// <returns></returns>
        public static string GetEnumNameValueString(this Enum emObj)
        {
            var type     = emObj.GetType();
            var typeName = type.Name;
            ///var valueNames = Enum.GetNames(type, emObj);
            var flagValues = Enum.GetValues(type)
                             .Cast <Enum>()
                             .Where(m => emObj.HasFlag(m));

            List <string> lst_Names = new List <string>();

            foreach (var itemEnumValue in flagValues)
            {
                var valueName = Enum.GetName(type, itemEnumValue);
                lst_Names.Add(valueName);
            }
            string names = string.Join(":", lst_Names.ToArray());

            return(string.Concat(typeName, ":", names));
        }
Esempio n. 14
0
        static StackObject *HasFlag_2(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Enum @flag = (System.Enum) typeof(System.Enum).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Enum instance_of_this_method = (System.Enum) typeof(System.Enum).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.HasFlag(@flag);

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method ? 1 : 0;
            return(__ret + 1);
        }
Esempio n. 15
0
        /// <summary>
        /// 将一个标记了 <see cref="FlagsAttribute "/> 特性的枚举值分解成其包含已合并的多个该类型的枚举值。
        /// 例如通过对枚举值 BindingFlags.GetField | BindingFlags.GetProperty 指定该方法,将会返回一个数组 { BindingFlags.GetField, BindingFlags.GetProperty }。
        /// 如果传入的枚举参数所属的枚举类型未标记 <see cref="FlagsAttribute "/> 特性,该方法将会抛出异常。
        /// </summary>
        /// <param name="_this"></param>
        /// <returns></returns>
        public static Enum[] Decompose(this System.Enum _this)
        {
            Type thisType = _this.GetType();

            if (!_this.IsDefinedFlags())
            {
                throw new ArgumentException(string.Format("传入的枚举值 {0} 其类型为 {1},未定义标记特性 FlagsAttribute。", _this, thisType));
            }

            Enum[]      enums = Enums.GetFields(thisType);
            List <Enum> list  = new List <Enum>();

            foreach (Enum item in enums)
            {
                if (_this.HasFlag(item))
                {
                    list.Add(item);
                }
            }
            return(list.ToArray());
        }
Esempio n. 16
0
 public static void AdjustBinding(string hotkeyName, Enum key, Dictionary<string, Hotkey> dict)
 {
     dict[hotkeyName].Key = (Keys)key;
     dict[hotkeyName].Ctrl = key.HasFlag(Keys.Control);
     dict[hotkeyName].Alt = key.HasFlag(Keys.Alt);
     dict[hotkeyName].Shift = key.HasFlag(Keys.Shift);
 }
Esempio n. 17
0
 public static bool Includes(this Enum @this, Enum that)
 {
     return(@this.HasFlag(that));
 }
Esempio n. 18
0
 public static bool HasFlag(Enum value, Enum flag)
 {
     //Added in .NET 4.0
     return value.HasFlag(flag);
 }
Esempio n. 19
0
        /// <summary>
        /// Checks if input has only one of the values set.
        /// </summary>
        /// <param name="input">The input value.</param>
        /// <param name="values">The values to check against.</param>
        /// <returns>Returns true if input has only one of the values, false otherwise.</returns>
        private bool EnumHasOnlyOne(Enum input, params Enum[] values)
        {
            if (values.Length < 1)
                return false;

            var hasFlag = false;

            foreach (var value in values) {
                if (input.HasFlag(value)) {
                    if (hasFlag)
                        return false;
                    else
                        hasFlag = true;
                }
            }

            return hasFlag;
        }
Esempio n. 20
0
 public static void HasFlag(Enum e, Enum flag, bool expected)
 {
     Assert.Equal(expected, e.HasFlag(flag));
 }
 static IEnumerable<Enum> GetFlags(Enum input)
 {
     foreach (Enum value in Enum.GetValues(input.GetType()))
         if (input.HasFlag(value))
             yield return value;
 }
Esempio n. 22
0
		public static string Resolve(Enum e)
		{
			if (e is Consistency)
			{ 
				switch((Consistency)e)
				{
					case Consistency.One: return "one";
					case Consistency.Quorum: return "quorum";
					case Consistency.All: return "all";
				}
			
			}
			
			if (e is Bytes)
			{ 
				switch((Bytes)e)
				{
					case Bytes.B: return "b";
					case Bytes.K: return "k";
					case Bytes.Kb: return "kb";
					case Bytes.M: return "m";
					case Bytes.Mb: return "mb";
					case Bytes.G: return "g";
					case Bytes.Gb: return "gb";
					case Bytes.T: return "t";
					case Bytes.Tb: return "tb";
					case Bytes.P: return "p";
					case Bytes.Pb: return "pb";
				}
			
			}
			
			if (e is Size)
			{ 
				switch((Size)e)
				{
					case Size.Raw: return "";
					case Size.K: return "k";
					case Size.M: return "m";
					case Size.G: return "g";
					case Size.T: return "t";
					case Size.P: return "p";
				}
			
			}
			
			if (e is Level)
			{ 
				switch((Level)e)
				{
					case Level.Cluster: return "cluster";
					case Level.Indices: return "indices";
					case Level.Shards: return "shards";
				}
			
			}
			
			if (e is WaitForStatus)
			{ 
				switch((WaitForStatus)e)
				{
					case WaitForStatus.Green: return "green";
					case WaitForStatus.Yellow: return "yellow";
					case WaitForStatus.Red: return "red";
				}
			
			}
			
			if (e is ExpandWildcards)
			{ 
				switch((ExpandWildcards)e)
				{
					case ExpandWildcards.Open: return "open";
					case ExpandWildcards.Closed: return "closed";
					case ExpandWildcards.None: return "none";
					case ExpandWildcards.All: return "all";
				}
			
			}
			
			if (e is DefaultOperator)
			{ 
				switch((DefaultOperator)e)
				{
					case DefaultOperator.And: return "AND";
					case DefaultOperator.Or: return "OR";
				}
			
			}
			
			if (e is VersionType)
			{ 
				switch((VersionType)e)
				{
					case VersionType.Internal: return "internal";
					case VersionType.External: return "external";
					case VersionType.ExternalGte: return "external_gte";
					case VersionType.Force: return "force";
				}
			
			}
			
			if (e is Conflicts)
			{ 
				switch((Conflicts)e)
				{
					case Conflicts.Abort: return "abort";
					case Conflicts.Proceed: return "proceed";
				}
			
			}
			
			if (e is SearchType)
			{ 
				switch((SearchType)e)
				{
					case SearchType.QueryThenFetch: return "query_then_fetch";
					case SearchType.DfsQueryThenFetch: return "dfs_query_then_fetch";
				}
			
			}
			
			if (e is SuggestMode)
			{ 
				switch((SuggestMode)e)
				{
					case SuggestMode.Missing: return "missing";
					case SuggestMode.Popular: return "popular";
					case SuggestMode.Always: return "always";
				}
			
			}
			
			if (e is OpType)
			{ 
				switch((OpType)e)
				{
					case OpType.Index: return "index";
					case OpType.Create: return "create";
				}
			
			}
			
			if (e is Format)
			{ 
				switch((Format)e)
				{
					case Format.Detailed: return "detailed";
					case Format.Text: return "text";
				}
			
			}
			
			if (e is ThreadType)
			{ 
				switch((ThreadType)e)
				{
					case ThreadType.Cpu: return "cpu";
					case ThreadType.Wait: return "wait";
					case ThreadType.Block: return "block";
				}
			
			}
			
			if (e is PercolateFormat)
			{ 
				switch((PercolateFormat)e)
				{
					case PercolateFormat.Ids: return "ids";
				}
			
			}
			
			if (e is GroupBy)
			{ 
				switch((GroupBy)e)
				{
					case GroupBy.Nodes: return "nodes";
					case GroupBy.Parents: return "parents";
				}
			
			}
			
			if (e is ClusterStateMetric)
			{ 
				var list = new List<string>();
				if (e.HasFlag(ClusterStateMetric.Blocks)) list.Add("blocks");
				if (e.HasFlag(ClusterStateMetric.Metadata)) list.Add("metadata");
				if (e.HasFlag(ClusterStateMetric.Nodes)) list.Add("nodes");
				if (e.HasFlag(ClusterStateMetric.RoutingTable)) list.Add("routing_table");
				if (e.HasFlag(ClusterStateMetric.RoutingNodes)) list.Add("routing_nodes");
				if (e.HasFlag(ClusterStateMetric.MasterNode)) list.Add("master_node");
				if (e.HasFlag(ClusterStateMetric.Version)) list.Add("version");
				if (e.HasFlag(ClusterStateMetric.All)) return "_all";
				return string.Join(",", list);
			
			}
			
			if (e is Feature)
			{ 
				var list = new List<string>();
				if (e.HasFlag(Feature.Settings)) list.Add("_settings");
				if (e.HasFlag(Feature.Mappings)) list.Add("_mappings");
				if (e.HasFlag(Feature.Aliases)) list.Add("_aliases");
				return string.Join(",", list);
			
			}
			
			if (e is IndicesStatsMetric)
			{ 
				var list = new List<string>();
				if (e.HasFlag(IndicesStatsMetric.Completion)) list.Add("completion");
				if (e.HasFlag(IndicesStatsMetric.Docs)) list.Add("docs");
				if (e.HasFlag(IndicesStatsMetric.Fielddata)) list.Add("fielddata");
				if (e.HasFlag(IndicesStatsMetric.QueryCache)) list.Add("query_cache");
				if (e.HasFlag(IndicesStatsMetric.Flush)) list.Add("flush");
				if (e.HasFlag(IndicesStatsMetric.Get)) list.Add("get");
				if (e.HasFlag(IndicesStatsMetric.Indexing)) list.Add("indexing");
				if (e.HasFlag(IndicesStatsMetric.Merge)) list.Add("merge");
				if (e.HasFlag(IndicesStatsMetric.Percolate)) list.Add("percolate");
				if (e.HasFlag(IndicesStatsMetric.RequestCache)) list.Add("request_cache");
				if (e.HasFlag(IndicesStatsMetric.Refresh)) list.Add("refresh");
				if (e.HasFlag(IndicesStatsMetric.Search)) list.Add("search");
				if (e.HasFlag(IndicesStatsMetric.Segments)) list.Add("segments");
				if (e.HasFlag(IndicesStatsMetric.Store)) list.Add("store");
				if (e.HasFlag(IndicesStatsMetric.Warmer)) list.Add("warmer");
				if (e.HasFlag(IndicesStatsMetric.Suggest)) list.Add("suggest");
				if (e.HasFlag(IndicesStatsMetric.All)) return "_all";
				return string.Join(",", list);
			
			}
			
			if (e is NodesInfoMetric)
			{ 
				var list = new List<string>();
				if (e.HasFlag(NodesInfoMetric.Settings)) list.Add("settings");
				if (e.HasFlag(NodesInfoMetric.Os)) list.Add("os");
				if (e.HasFlag(NodesInfoMetric.Process)) list.Add("process");
				if (e.HasFlag(NodesInfoMetric.Jvm)) list.Add("jvm");
				if (e.HasFlag(NodesInfoMetric.ThreadPool)) list.Add("thread_pool");
				if (e.HasFlag(NodesInfoMetric.Transport)) list.Add("transport");
				if (e.HasFlag(NodesInfoMetric.Http)) list.Add("http");
				if (e.HasFlag(NodesInfoMetric.Plugins)) list.Add("plugins");
				if (e.HasFlag(NodesInfoMetric.Ingest)) list.Add("ingest");
				return string.Join(",", list);
			
			}
			
			if (e is NodesStatsMetric)
			{ 
				var list = new List<string>();
				if (e.HasFlag(NodesStatsMetric.Breaker)) list.Add("breaker");
				if (e.HasFlag(NodesStatsMetric.Fs)) list.Add("fs");
				if (e.HasFlag(NodesStatsMetric.Http)) list.Add("http");
				if (e.HasFlag(NodesStatsMetric.Indices)) list.Add("indices");
				if (e.HasFlag(NodesStatsMetric.Jvm)) list.Add("jvm");
				if (e.HasFlag(NodesStatsMetric.Os)) list.Add("os");
				if (e.HasFlag(NodesStatsMetric.Process)) list.Add("process");
				if (e.HasFlag(NodesStatsMetric.ThreadPool)) list.Add("thread_pool");
				if (e.HasFlag(NodesStatsMetric.Transport)) list.Add("transport");
				if (e.HasFlag(NodesStatsMetric.Discovery)) list.Add("discovery");
				if (e.HasFlag(NodesStatsMetric.All)) return "_all";
				return string.Join(",", list);
			
			}
			
			if (e is NodesStatsIndexMetric)
			{ 
				var list = new List<string>();
				if (e.HasFlag(NodesStatsIndexMetric.Completion)) list.Add("completion");
				if (e.HasFlag(NodesStatsIndexMetric.Docs)) list.Add("docs");
				if (e.HasFlag(NodesStatsIndexMetric.Fielddata)) list.Add("fielddata");
				if (e.HasFlag(NodesStatsIndexMetric.QueryCache)) list.Add("query_cache");
				if (e.HasFlag(NodesStatsIndexMetric.Flush)) list.Add("flush");
				if (e.HasFlag(NodesStatsIndexMetric.Get)) list.Add("get");
				if (e.HasFlag(NodesStatsIndexMetric.Indexing)) list.Add("indexing");
				if (e.HasFlag(NodesStatsIndexMetric.Merge)) list.Add("merge");
				if (e.HasFlag(NodesStatsIndexMetric.Percolate)) list.Add("percolate");
				if (e.HasFlag(NodesStatsIndexMetric.RequestCache)) list.Add("request_cache");
				if (e.HasFlag(NodesStatsIndexMetric.Refresh)) list.Add("refresh");
				if (e.HasFlag(NodesStatsIndexMetric.Search)) list.Add("search");
				if (e.HasFlag(NodesStatsIndexMetric.Segments)) list.Add("segments");
				if (e.HasFlag(NodesStatsIndexMetric.Store)) list.Add("store");
				if (e.HasFlag(NodesStatsIndexMetric.Warmer)) list.Add("warmer");
				if (e.HasFlag(NodesStatsIndexMetric.Suggest)) list.Add("suggest");
				if (e.HasFlag(NodesStatsIndexMetric.All)) return "_all";
				return string.Join(",", list);
			
			}
			
			return UnknownEnum;
		}
Esempio n. 23
0
 /// <summary>
 /// 获取枚举值包含的位域值
 /// </summary>
 /// <param name="e"></param>
 /// <returns></returns>
 public static IEnumerable <Enum> GetFlagEnums(this Enum e)
 {
     return(e.GetHashCode() == 0 ? (new Enum[0]) : e.GetValues().Where(item => e.HasFlag(item)));
 }
		/// ------------------------------------------------------------------------------------
// ReSharper disable once UnusedParameter.Local
		private void PreventInvalidAudienceTypeForWorkStage(Enum invalidAudience, WorkStage stage)
		{
			if ((invalidAudience != null) && (invalidAudience.HasFlag(_metsAudienceType)))
			{
				throw new InvalidOperationException(string.Format(
					"Resources with an audience of \"{0}\" cannot have a work stage of {1}",
					_metsAudienceType, stage));
			}
		}
Esempio n. 25
0
 /// <summary>
 ///     Iterate over the bit values in enum property.
 /// </summary>
 private static IEnumerable<string> GetFlags(Enum input)
 {
     foreach (Enum value in Enum.GetValues(input.GetType()))
         if (input.HasFlag(value))
             yield return value.ToString();
 }