GetEnumValues() public method

public GetEnumValues ( ) : Array
return Array
Ejemplo n.º 1
0
 public EnumConfiguration(Type enumType)
 {
     _signed = IsSignedEnum(enumType);
     _flags = IsFlagsEnum(enumType);
     _names = enumType.GetEnumNames();
     var members = enumType.GetMembers(BindingFlags.Static | BindingFlags.Public);
     Debug.Assert(members.Length == _names.Length);
     for (int i = 0; i < members.Length; i++)
     {
         var a = members[i].GetCustomAttributes<PersistedNameAttribute>().FirstOrDefault();
         if (a != null) _names[i] = a.Name;
     }
     var undertype = enumType.GetEnumUnderlyingType();
     var enumValues = enumType.GetEnumValues();
     IEnumerable<ulong> enumValuesUlongs;
     if (undertype == typeof(int)) enumValuesUlongs = enumValues.Cast<int>().Select(i => (ulong)i);
     else if (undertype == typeof(uint)) enumValuesUlongs = enumValues.Cast<uint>().Select(i => (ulong)i);
     else if (undertype == typeof(sbyte)) enumValuesUlongs = enumValues.Cast<sbyte>().Select(i => (ulong)i);
     else if (undertype == typeof(byte)) enumValuesUlongs = enumValues.Cast<byte>().Select(i => (ulong)i);
     else if (undertype == typeof(short)) enumValuesUlongs = enumValues.Cast<short>().Select(i => (ulong)i);
     else if (undertype == typeof(ushort)) enumValuesUlongs = enumValues.Cast<ushort>().Select(i => (ulong)i);
     else if (undertype == typeof(long)) enumValuesUlongs = enumValues.Cast<long>().Select(i => (ulong)i);
     else enumValuesUlongs = enumValues.Cast<ulong>();
     _values = enumValuesUlongs.ToArray();
 }
 public static IDictionary<object, string> GetEnumAsDict(Type enumType)
 {
     var dict = new Dictionary<object, string>();
     foreach (var val in enumType.GetEnumValues())
         dict.Add(val, val.ToString());
     return dict;
 }
Ejemplo n.º 3
0
        //=============================================================
        //    Public static methods
        //=============================================================
        /// <summary>
        /// NOTE: Returns one Description value for each enumerator value.
        /// </summary>
        /// <param name="type">Type of enum.</param>
        /// <returns>Array of descriptions.</returns>
        /// <exception cref="ArgumentNullException">Thrown when type is null.</exception>
        /// <exception cref="ArgumentException">Thrown when type is not enumerator.</exception>
        public static string[] GetDescriptionValues(Type type)
        {
            if (type == null) throw new ArgumentNullException("type");
            if (!type.IsEnum) throw new ArgumentException(@"Type is not enumerator.", "type");

            return (from object enumValue in type.GetEnumValues() select GetEnumDescription((Enum)enumValue)).ToArray();
        }
Ejemplo n.º 4
0
 public static Array GetValues(Type enumType)
 {
     if (enumType == null)
     {
         throw new ArgumentNullException("enumType");
     }
     return(enumType.GetEnumValues());
 }
Ejemplo n.º 5
0
        public static Array GetEnumValues(System.Type type)
        {
#if USE_HOT
            if (type is ILRuntime.Reflection.ILRuntimeType)
            {
                return(Get(type).allValues);
            }
#endif
            return(type.GetEnumValues());
        }
Ejemplo n.º 6
0
        private void FillKeyOptions()
        {
            System.Type keyTypes  = typeof(Keys);
            Keys[]      keyValues = (Keys[])keyTypes.GetEnumValues();

            foreach (Keys targetKey in keyValues)
            {
                plotUnzoomKeyComboBox.Items.Add(targetKey);
            }
        }
Ejemplo n.º 7
0
        static int[] GetIntegerValueArray(System.Type enumType)
        {
            var valueArray = enumType.GetEnumValues();
            var intValues  = new int[valueArray.Length];

            for (int iValue = 0; iValue < valueArray.Length; iValue++)
            {
                intValues[iValue] = (int)valueArray.GetValue(iValue);
            }
            return(intValues);
        }
Ejemplo n.º 8
0
    private void GenerateUnit()
    {
        sr = GetComponent <Image>();

        unit_sex = Random.Range(0, 2);
        if (unit_sex == 0)  //Male
        {
            unit_name = male_names[Random.Range(0, male_names.Length)];
        }
        else  //female
        {
            unit_name = female_names[Random.Range(0, female_names.Length)];
        }
        pronoun = sex[unit_sex];
        possessive_selection = possessive_sex[unit_sex];
        himhers      = sexo[unit_sex];
        unit_surname = surnames[Random.Range(0, surnames.Length)];

        stats = new Dictionary <UnitStat, int> {
            { UnitStat.cooking, Random.Range(0, 3) },
            { UnitStat.engineering, Random.Range(1, 3) },
            { UnitStat.combat, Random.Range(0, 3) },
            { UnitStat.skillpoints, 0 },
            { UnitStat.xp, 0 },
            { UnitStat.level, 1 },
            { UnitStat.hp, 10 },
            { UnitStat.italy, Random.Range(0, 3) },
            { UnitStat.happiness, 5 }
        };
        System.Type  type   = typeof(UnitType);
        System.Array values = type.GetEnumValues();
        int          index  = Random.Range(0, values.Length);

        unit_type = (UnitType)values.GetValue(index);
        switch (unit_type)
        {
        case UnitType.Cook:
            sr.color = new Color(0, 0.8f, 0);
            break;

        case UnitType.Electrician:
            sr.color = new Color(0, 0.7f, 0.7f);
            break;

        case UnitType.Explorer:
            sr.color = new Color(0.6f, 0, 0.6f);
            break;

        case UnitType.Engingeer:
            sr.color = new Color(0, 0, 0.6f);
            break;
        }
        GenerateBio();
    }
Ejemplo n.º 9
0
        public static Array GetValues(Type enumType)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }
            Contract.Ensures(Contract.Result <Array>() != null);
            Contract.EndContractBlock();

            return(enumType.GetEnumValues());
        }
Ejemplo n.º 10
0
        protected override List<IObjectInstance> GetEnumTestValues(Type type)
        {
            List<IObjectInstance> vals = new List<IObjectInstance>();

            foreach (object enumValue in type.GetEnumValues())
            {
                vals.Add(new ObjectInstance(enumValue));
            }

            return vals;
        }
Ejemplo n.º 11
0
 private static void GenerateEnum(StringBuilder stringBuilder, Type type)
 {
     stringBuilder.AppendLine();
     stringBuilder.AppendFormat("\texport enum {0}", type.Name);
     stringBuilder.AppendLine("{");
     foreach (int enumValue in type.GetEnumValues())
     {
         var name = type.GetEnumName(enumValue);
         stringBuilder.AppendLine(string.Format("{0} = {1},", name, enumValue));
     }
     stringBuilder.AppendLine("}");
 }
Ejemplo n.º 12
0
 private static object FromString(Type t, string str)
 {
     if (t.IsEnum)
     {
         return t.GetEnumValues().OfType<Enum>().FirstOrDefault(x => String.Equals(str, x.ToString(), StringComparison.CurrentCultureIgnoreCase))
                ?? t.GetEnumValues().OfType<Enum>().FirstOrDefault();
     }
     if (t == typeof(decimal))
     {
         // Settings were saved with culture before, need backwards compatibility
         str = str.Replace(',', '.');
     }
     if (t == typeof(Color))
     {
         var spl = str.Split(' ');
         int r, g, b;
         int.TryParse(spl[0], out r);
         int.TryParse(spl[1], out g);
         int.TryParse(spl[2], out b);
         return Color.FromArgb(r, g, b);
     }
     return Convert.ChangeType(str, t, CultureInfo.InvariantCulture);
 }
Ejemplo n.º 13
0
        public static int ParseEnum(Type type, string tag)
        {
            int value;

            if (int.TryParse(tag, out value))
            {
                return(value);
            }
            var index = type.GetEnumNames().ToList().IndexOf(tag);

            if (index > -1)
            {
                return((int)type.GetEnumValues().GetValue(index));
            }
            throw new Exception("Enum not found: " + tag);
        }
Ejemplo n.º 14
0
        public static string[] GetDisplayStrings(this Type enumType)
        {
            List <string> list = new List <string>();

            foreach (object value in enumType.GetEnumValues())
            {
                string name = Enum.GetName(enumType, value);
                if (name != null)
                {
                    FieldInfo field = enumType.GetField(name);
                    if (field != null)
                    {
                        DescriptionAttribute?attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                        list.Add(attr != null ? attr.Description : Regex.Replace(field.Name, " "));
                    }
                }
            }

            return(list.ToArray());
        }
Ejemplo n.º 15
0
 public EnumTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type)
 {
     _typeSerializers = typeSerializers;
     _type = type;
     _name = typeSerializers.TypeNameMapper.ToName(type);
     _signed = IsSignedEnum(type);
     _flags = IsFlagsEnum(type);
     var undertype = type.GetEnumUnderlyingType();
     var enumValues = type.GetEnumValues();
     IEnumerable<ulong> enumValuesUlongs;
     if (undertype == typeof(int)) enumValuesUlongs = enumValues.Cast<int>().Select(i => (ulong)i);
     else if (undertype == typeof(uint)) enumValuesUlongs = enumValues.Cast<uint>().Select(i => (ulong)i);
     else if (undertype == typeof(sbyte)) enumValuesUlongs = enumValues.Cast<sbyte>().Select(i => (ulong)i);
     else if (undertype == typeof(byte)) enumValuesUlongs = enumValues.Cast<byte>().Select(i => (ulong)i);
     else if (undertype == typeof(short)) enumValuesUlongs = enumValues.Cast<short>().Select(i => (ulong)i);
     else if (undertype == typeof(ushort)) enumValuesUlongs = enumValues.Cast<ushort>().Select(i => (ulong)i);
     else if (undertype == typeof(long)) enumValuesUlongs = enumValues.Cast<long>().Select(i => (ulong)i);
     else enumValuesUlongs = enumValues.Cast<ulong>();
     _pairs = type.GetEnumNames().Zip(enumValuesUlongs.ToArray(), (s, v) => new KeyValuePair<string, ulong>(s, v)).ToList();
 }
Ejemplo n.º 16
0
        public static int GetMaxEnumValue(System.Type type)
        {
#if USE_HOT
            if (type is ILRuntime.Reflection.ILRuntimeType)
            {
                return(Get(type).GetMaxValue());
            }
#endif
            int maxValue = 0;
            foreach (var ator in type.GetEnumValues())
            {
                int v = (int)ator;
                if (v > maxValue)
                {
                    maxValue = v;
                }
            }

            return(maxValue);
        }
Ejemplo n.º 17
0
        private void Initialize(Assembly assembly, string amsNetIdTarget, ushort amsPortTarget)
        {
            t_TcAdsClient = assembly.GetType("TwinCAT.Ads.TcAdsClient");
            t_AdsStream = assembly.GetType("TwinCAT.Ads.AdsStream");
            t_StateInfo = assembly.GetType("TwinCAT.Ads.StateInfo");
            t_DeviceInfo = assembly.GetType("TwinCAT.Ads.DeviceInfo");
            t_AdsVersion = assembly.GetType("TwinCAT.Ads.AdsVersion");
            t_AdsTransMode = assembly.GetType("TwinCAT.Ads.AdsTransMode");

            adsTransMode = Activator.CreateInstance(t_AdsTransMode);

            Array n = t_AdsTransMode.GetEnumNames();
            Array v = t_AdsTransMode.GetEnumValues();
            int c = n.Length;
            for (int i = 0; i < c; i++)
            {
                if ((string)n.GetValue(i) == "Cyclic")
                    AdsTransMode_Cyclic = v.GetValue(i);
                else
                    if ((string)n.GetValue(i) == "OnChange")
                        AdsTransMode_OnChange = v.GetValue(i);
            }

            client = Activator.CreateInstance(t_TcAdsClient);
            client.Connect(amsNetIdTarget, amsPortTarget);

            var this_eventHandler =
                typeof(AdsClient).GetMethod(
                    "TcAdsClient_AdsNotification",
                    BindingFlags.Instance | BindingFlags.NonPublic);

            client.AdsNotification +=
                (dynamic)Delegate.CreateDelegate(
                        t_TcAdsClient.GetEvent("AdsNotification").EventHandlerType,
                        this,
                        this_eventHandler);
        }
        public static List<EnumNameValuePair> EnumToList(Type enumtype)
        {
            var valuelist = enumtype.GetEnumValues();
            var source = new List<EnumNameValuePair>();
            foreach (var v in valuelist)
            {
                var sitem = new EnumNameValuePair();
                sitem.Value = v;

                var member = enumtype.GetMember(v.ToString())[0];
                var attr = member.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
                if (attr != null)
                {
                    sitem.Name = attr.Name;
                    sitem.Description = attr.Description;
                }
                else
                    sitem.Name = v.ToString();

                source.Add(sitem);
            }

            return source;
        }
Ejemplo n.º 19
0
 protected void GenerateEnumDocumentation(Type type)
 {
     UserStream.WriteLine("=> Generating documentation for type {0}", type.Name);
     Output.WriteLine("<h4 name=\"{0}\">{0} (enumeration)</h4>", type.Name);
     Output.WriteLine("<dl><dt>Values</dt><dd><ul>");
     foreach (var val in type.GetEnumValues())
     {
         Output.WriteLine("<li>{0}: {1}</li>", type.GetEnumName(val), (int)val);
     }
     Output.WriteLine("</ul></dt></dl>");
 }
Ejemplo n.º 20
0
        private Schema CreateEnumSchema(JsonPrimitiveContract primitiveContract, Type type)
        {
            var stringEnumConverter = primitiveContract.Converter as StringEnumConverter
                ?? _jsonSerializerSettings.Converters.OfType<StringEnumConverter>().FirstOrDefault();

            if (_describeAllEnumsAsStrings || stringEnumConverter != null || _autoRestEnumSupport != null)
            {
                var camelCase = _describeStringEnumsInCamelCase
                    || (stringEnumConverter != null && stringEnumConverter.CamelCaseText);

                return new Schema
                {
                    type = "string",
                    @enum = camelCase
                        ? type.GetEnumNamesForSerialization().Select(name => name.ToCamelCase()).ToArray()
                        : type.GetEnumNamesForSerialization(),
                    xmsenum = _autoRestEnumSupport != null ? new MSEnumExtension
                        {
                            name = type.Name,
                            modelAsString = _autoRestEnumSupport == AutoRestEnumSupportType.StaticStrings,
                        } : null
                };
            }
            
            return new Schema
            {
                type = "integer",
                format = "int32",
                @enum = type.GetEnumValues().Cast<object>().ToArray()
            };
        }
Ejemplo n.º 21
0
 /// <summary>
 /// 判断枚举值是否包含
 /// </summary>
 /// <param name="value">值</param>
 /// <param name="type">枚举类型</param>
 /// <returns></returns>
 public static bool IsEnumContainsValue(this object value, Type type)
 {
     return value.IsInArray(type.GetEnumValues());
 }
Ejemplo n.º 22
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     // Nullable enums will cause a lot of trouble downstream if not converted to the underlying type
     if (Nullable.GetUnderlyingType(objectType) != null)
     {
         objectType = Nullable.GetUnderlyingType(objectType);
     }
     foreach (var val in objectType.GetEnumValues())
     {
         string name = Enum.GetName(objectType, val);
         FieldInfo field = objectType.GetField(name);
         DescriptionAttribute desc = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
         string description = desc.Description.ToLower();
         string readerValue = reader.Value.ToString().ToLower();
         if (description.Equals(readerValue))
         {
             return val;
         }
     }
     // If could not convert
     return base.ReadJson(reader, objectType, existingValue, serializer);
 }
Ejemplo n.º 23
0
            public override void Establish(IAutoBinder binder)
            {
                if (_allocated)
                    return;

                _brAltFlagP = (SLVSignal)binder.GetSignal(EPortUsage.Default, "BCU_BrP", null, StdLogicVector._0s(1));
                _brAltFlagN = (SLVSignal)binder.GetSignal(EPortUsage.Default, "BCU_BrN", null, StdLogicVector._1s(1));

                _curState = binder.GetSignal(EPortUsage.State, "BCU_CurState", null, null).Descriptor;
                _tState = _curState.ElementType.CILType;
                Array enumValues = _tState.GetEnumValues();
                int numStates = enumValues.Length;
                object defaultState = Activator.CreateInstance(_tState);
                _incState = binder.GetSignal(EPortUsage.Default, "BCU_IncState", null, defaultState).Descriptor;
                _altState = binder.GetSignal(EPortUsage.Default, "BCU_AltState", null, defaultState).Descriptor;
                _nextState = binder.GetSignal(EPortUsage.Default, "BCU_NextState", null, defaultState).Descriptor;
                IncStateProcessBuilder ispb = new IncStateProcessBuilder(this);
                Function incStateFn = ispb.GetAlgorithm();
                incStateFn.Name = "BCU_IncState";
                binder.CreateProcess(Process.EProcessKind.Triggered, incStateFn, _curState);
                SyncProcessBuilder spb = new SyncProcessBuilder(this, binder);
                Function syncStateFn = spb.GetAlgorithm();
                syncStateFn.Name = "BCU_FSM";
                ISignalOrPortDescriptor sdClock = binder.GetSignal<StdLogic>(EPortUsage.Clock, "Clk", null, '0').Descriptor;
                binder.CreateProcess(Process.EProcessKind.Triggered, syncStateFn, sdClock);

                _allocated = true;
            }
Ejemplo n.º 24
0
        public static void GenerateEnumCode(Type enumType)
        {
            if (!enumType.IsEnum)
                return;

            if (_typeNames.Contains(enumType.Name))
                return;

            _typeNames.Add(enumType.Name);

            Console.WriteLine(enumType.Name + " Generate Start");

            StringBuilder sb = new StringBuilder();
            sb.Append(_enumHeadText);
            sb.Append("\n");

            sb.Append("enum " + enumType.Name + "\n");
            sb.Append("{\n");
            foreach (object value in enumType.GetEnumValues())
            {
                sb.AppendFormat("{0} = {1},\n", enumType.GetEnumName(value), (int)value);
            }

            sb.Append("}\n");

            _exportFiles.Add(enumType.Name, sb.ToString());

            Console.WriteLine(enumType.Name + " Generate Success");
        }
Ejemplo n.º 25
0
        public static void SetDropDownSelect(
            this PropertyInfo p, List <DropDownViewModel> selector, Type relatedType, string postValue, IEnumerable <string> postValues = null)
        {
            List <String> values;

            if (postValues != null && postValues.Count() > 0)
            {
                values = postValues.ToList();
            }
            else
            {
                values = !String.IsNullOrEmpty(postValue) ? new List <string>()
                {
                    postValue
                } : new List <string>();
            }

            if (relatedType.IsEnum)
            {
                Array enumValues = relatedType.GetEnumValues();
                foreach (var item in enumValues)
                {
                    var select = new DropDownViewModel();
                    select.Name   = item.ToString();
                    select.Value  = item.ToString();
                    select.Select = values.Contains(select.Value);
                    selector.Add(select);
                }
            }
            else
            {
                //dropdown Classes
                var isContent = relatedType.GetInterfaces().Any(b => b == typeof(IInt64Key));
                if (isContent)
                {
                    var allSelect = BaseCruds.Read <IBasicContent>(relatedType, b => true).ToList();

                    var selects = new List <DropDownViewModel>();
                    foreach (var item in allSelect)
                    {
                        var select = new DropDownViewModel();
                        select.Name   = item.DisplayName();
                        select.Value  = item.Id.ToString();
                        select.Select = values.Contains(select.Value);
                        selector.Add(select);
                    }
                }
                else
                {
                    var allSelect = BaseCruds.Read <IStringKey>(relatedType, b => true).ToList();

                    var selects = new List <DropDownViewModel>();
                    foreach (var item in allSelect)
                    {
                        var select = new DropDownViewModel();
                        select.Name   = item.ToString();
                        select.Value  = item.Id;
                        select.Select = values.Contains(select.Value);
                        selector.Add(select);
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public static TEnum[] GetValues <TEnum>() where TEnum : struct
        {
            Type enumType = typeof(TEnum);

            return((TEnum[])enumType.GetEnumValues());
        }
Ejemplo n.º 27
0
        private string CType(Type t, UnmanagedType? customType = null) {
            switch (t.Name) {
                case "Byte":
                case "byte":
                    return "unsigned __int8";
                case "SByte":
                case "sbyte":
                    return "__int8";
                case "int":
                case "Int32":
                    return "__int32";
                case "uint":
                case "UInt32":
                    return "unsigned __int32";
                case "Int16":
                case "short":
                    return "__int16";
                case "UInt16":
                case "ushort":
                    return "unsigned __int16";
                case "Int64":
                case "long":
                    return "__int64";
                case "UInt64":
                case "ulong":
                    return "unsigned __int64";
                case "Single":
                case "float":
                    return "float";
                case "Double":
                case "double":
                    return "double";
                case "Char":
                case "char":
                    return "wchar_t";
                case "bool":
                case "Boolean":
                    return "bool";
                case "string":
                case "String":
                    if (customType.HasValue && customType.Value == UnmanagedType.LPWStr) {
                        return "const wchar_t*";
                    }
                    return "const char_t*";


                case "IntPtr":
                    return "void*";
            }

            if (t.IsEnum) {
                if (enumTypeDefs.ContainsKey(t.Name)) {
                    return t.Name;
                }
                var enumType = CType(t.GetEnumUnderlyingType());


                var enumValues = t.GetEnumValues();

                var first = true;
                var evitems = string.Empty;
                foreach (var ev in enumValues) {
                    evitems += "{2}\r\n    {0} = {1}".format(t.GetEnumName(ev), (int) ev, first ? "" : ",");
                    first = false;
                }

                var tyepdefenum = "typedef enum  {{ {2}\r\n}} {0};\r\n".format(t.Name, enumType, evitems); /* : {1} */
                enumTypeDefs.Add(t.Name, tyepdefenum);
                return t.Name;
            }

            return "/* UNKNOWN : {0} */".format(t.Name);
        }
Ejemplo n.º 28
0
 public EnumSetting(object value, FieldInfo field, Type enumType, string group)
     : base(field, SettingType.Enum, group)
 {
     Value = value;
     EnumType = enumType;
     NumEnumValues = EnumType.GetEnumValues().Length;
     EnumTypeName = EnumType.Name;
 }
Ejemplo n.º 29
0
 private TsEnum GenerateEnum(Type type)
 {
     var names = type.GetEnumNames();
     var values = type.GetEnumValues();
     var entries = new Dictionary<string, long?>();
     for (int i = 0; i < values.Length; i++)
         entries.Add(names[i], Convert.ToInt64(values.GetValue(i)));
     var tsEnum = new TsEnum(GetName(type), entries);
     this.TypeLookup.Add(type, tsEnum);
     return tsEnum;
 }
Ejemplo n.º 30
0
        private Schema CreateEnumSchema(JsonPrimitiveContract primitiveContract, Type type)
        {
            var stringEnumConverter = primitiveContract.Converter as StringEnumConverter
                ?? _jsonSerializerSettings.Converters.OfType<StringEnumConverter>().FirstOrDefault();

            if (_describeAllEnumsAsStrings || stringEnumConverter != null)
            {
                var camelCase = _describeStringEnumsInCamelCase
                    || (stringEnumConverter != null && stringEnumConverter.CamelCaseText);

                return new Schema
                {
                    type = "string",
                    @enum = camelCase
                        ? type.GetEnumNames().Select(name => name.ToCamelCase()).ToArray()
                        : type.GetEnumNames()
                };
            }

            return new Schema
            {
                type = "integer",
                format = "int32",
                @enum = type.GetEnumValues().Cast<object>().ToArray()
            };
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Converts <paramref name="src"/> to the enumeration literal of <paramref name="dstType"/> whose ordinal number
        /// is <paramref name="src"/>. Values being a combination of multiple literals of a [Flag] enum are NOT supported.
        /// </summary>
        /// <param name="src">ordinal value</param>
        /// <param name="dstType">target enumeration type</param>
        /// <exception cref="ArgumentNullException">if <paramref name="dstType"/> is null</exception>
        /// <exception cref="ArgumentException">if <paramref name="dstType"/> is not an enum</exception>
        /// <exception cref="ArgumentOutOfRangeException">if there is no corresponding literal</exception>
        public static object ConvertToEnum(long src, Type dstType)
        {
            Contract.Requires<ArgumentNullException>(dstType != null, "dstType");
            Contract.Requires<ArgumentException>(dstType.IsEnum, "Destination type is not an enum type");

            Array enumValues = dstType.GetEnumValues();
            FieldInfo[] fields = dstType.GetFields(BindingFlags.Instance | BindingFlags.Public);
            FieldInfo valueField = fields[0];
            object conv = null;
            foreach (object enumValue in enumValues)
            {
                long lval = ToLong(valueField.GetValue(enumValue));
                if (lval == src)
                {
                    conv = enumValue;
                    break;
                }
            }
            if (conv == null)
                throw new ArgumentOutOfRangeException("No matching enum value");

            return conv;
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Retrieves an array of the values of the constants in a specified enumeration.
 /// </summary>
 /// 
 /// <returns>
 /// An array that contains the values of the constants in <paramref name="enumType"/>.
 /// </returns>
 /// <param name="enumType">An enumeration type. </param><exception cref="T:System.ArgumentNullException"><paramref name="enumType"/> is null. </exception><exception cref="T:System.ArgumentException"><paramref name="enumType"/> is not an <see cref="T:System.Enum"/>. </exception><exception cref="T:System.InvalidOperationException">The method is invoked by reflection in a reflection-only context, -or-<paramref name="enumType"/> is a type from an assembly loaded in a reflection-only context.</exception><filterpriority>1</filterpriority>
 public static Array GetValues(Type enumType)
 {
     if (enumType == null)
         throw new ArgumentNullException("enumType");
     else
         return enumType.GetEnumValues();
 }
Ejemplo n.º 33
0
        public string EnumToMarkdown(Type type)
        {
            var output = new StringBuilder();

            // Only print members that are documented
            if (!MemberDocumentations.ContainsKey(type.FullName))
                return "";

            var doc = MemberDocumentations[type.FullName];

            // Print the type name heading
            output.AppendLine("<a id=\"" + type.FullName + "\"></a>");
            output.AppendLine("## enum " + type.FullName);

            output.AppendLine("");

            // Print summary and remarks
            if (!String.IsNullOrEmpty(doc.Summary))
                output.AppendLine(doc.Summary);

            if (!String.IsNullOrEmpty(doc.Remarks))
                output.AppendLine(doc.Remarks);

            output.AppendLine("");

            var values = type.GetEnumValues();

            if (values.Length > 0)
            {
                output.AppendLine("**Enum Values**");
                output.AppendLine("");
                foreach (var value in values)
                {
                    var name = type.GetEnumName(value);
                    output.AppendLine("* **" + name + "**");
                }
            }

            output.AppendLine("");

            return output.ToString();
        }