Esempio n. 1
0
        private string HandleEnumType()
        {
            FlagsAttribute flags = t.GetCustomAttribute <FlagsAttribute>();

            if (flags != null)
            {
                CrIndentPush(sb);
                sb.Append("[FLAGS]: <");
                int numFlags = 0;
                foreach (Enum value in Enum.GetValues(t))
                {
                    if (((Enum)obj).HasFlag(value))
                    {
                        sb.AppendFormat($"{value.ToString()},");
                        numFlags++;
                    }
                }
                if (numFlags > 0)
                {
                    sb.Length--;
                }
                sb.Append(">");
            }
            else
            {
                sb.Append(Enum.GetName(t, obj));
            }

            return(sb.ToString());
        }
Esempio n. 2
0
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Ctor.");

        try
        {
            FlagsAttribute fa = new FlagsAttribute();

            if (fa == null)
            {
                TestLibrary.TestFramework.LogError("001.1", "Ctor Err !");
                retVal = false;
                return retVal;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 3
0
        public void ReadMeReflectedInformation()
        {
            // Shortcut for typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static)
            FieldInfo[] fields = EnumUtil.GetEnumFields <YourEnum>();

            // On the Enumeration itself
            FlagsAttribute attr = EnumUtil.GetAttribute <FlagsAttribute, YourEnum>();
            IEnumerable <DescriptionAttribute> attrs = EnumUtil.GetAttributes <DescriptionAttribute, YourEnum>();
            bool hasFlagsAttr     = EnumUtil.HasAttribute <FlagsAttribute, YourEnum>();
            bool hasFlagsShortcut = EnumUtil.HasFlagsAttribute <YourEnum>();

            // On a field in the enumeration
            DescriptionAttribute attr2 = EnumUtil.GetAttribute <DescriptionAttribute, YourEnum>(YourEnum.Bar);
            IEnumerable <DescriptionAttribute> attrs3 = EnumUtil.GetAttributes <DescriptionAttribute, YourEnum>(YourEnum.Bar);

            // Various Read Only Dictionaries
            // with data about the members of an enumeration
            var valueDescription     = EnumUtil.GetValueDescription <YourEnum>();
            var valueNameDescription = EnumUtil.GetValueNameDescription <YourEnum>();
            var valueNameAttributes  = EnumUtil.GetValueNameAttributes <YourEnum>();
            var nameValueAttribute   = EnumUtil.GetNameValueAttribute <YourEnum, DescriptionAttribute>();
            var valueNameAttribute   = EnumUtil.GetValueNameAttribute <YourEnum, DescriptionAttribute>();
            var valueAttribute       = EnumUtil.GetValueAttribute <YourEnum, DescriptionAttribute>();
            var nameValue            = EnumUtil.GetNameValue <YourEnum>();
            var valueName            = EnumUtil.GetValueName <YourEnum>();
        }
Esempio n. 4
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testBoth() throws Exception
        public virtual void testBoth()
        {
            ISet <string> untoks = new HashSet <string>();

            untoks.Add(WikipediaTokenizer.CATEGORY);
            untoks.Add(WikipediaTokenizer.ITALICS);
            string test = "[[Category:a b c d]] [[Category:e f g]] [[link here]] [[link there]] ''italics here'' something ''more italics'' [[Category:h   i   j]]";
            //should output all the indivual tokens plus the untokenized tokens as well.  Untokenized tokens
            WikipediaTokenizer tf = new WikipediaTokenizer(new StringReader(test), WikipediaTokenizer.BOTH, untoks);

            assertTokenStreamContents(tf, new string[] { "a b c d", "a", "b", "c", "d", "e f g", "e", "f", "g", "link", "here", "link", "there", "italics here", "italics", "here", "something", "more italics", "more", "italics", "h   i   j", "h", "i", "j" }, new int[] { 11, 11, 13, 15, 17, 32, 32, 34, 36, 42, 47, 56, 61, 71, 71, 79, 86, 98, 98, 103, 124, 124, 128, 132 }, new int[] { 18, 12, 14, 16, 18, 37, 33, 35, 37, 46, 51, 60, 66, 83, 78, 83, 95, 110, 102, 110, 133, 125, 129, 133 }, new int[] { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1 });

            // now check the flags, TODO: add way to check flags from BaseTokenStreamTestCase?
            tf = new WikipediaTokenizer(new StringReader(test), WikipediaTokenizer.BOTH, untoks);
            int[]          expectedFlags = new int[] { UNTOKENIZED_TOKEN_FLAG, 0, 0, 0, 0, UNTOKENIZED_TOKEN_FLAG, 0, 0, 0, 0, 0, 0, 0, UNTOKENIZED_TOKEN_FLAG, 0, 0, 0, UNTOKENIZED_TOKEN_FLAG, 0, 0, UNTOKENIZED_TOKEN_FLAG, 0, 0, 0 };
            FlagsAttribute flagsAtt      = tf.addAttribute(typeof(FlagsAttribute));

            tf.reset();
            for (int i = 0; i < expectedFlags.Length; i++)
            {
                assertTrue(tf.incrementToken());
                assertEquals("flags " + i, expectedFlags[i], flagsAtt.Flags);
            }
            assertFalse(tf.incrementToken());
            tf.close();
        }
Esempio n. 5
0
        protected void GetParamValueControlEnum()
        {
            _values.AddRange(Enum.GetValues(_type));

            FlagsAttribute flags = (FlagsAttribute)
                                   Attribute.GetCustomAttribute(_type,
                                                                typeof(FlagsAttribute));

            if (flags != null)
            {
                // A bit field
                CheckedListBox cb = new CheckedListBox();
                cb.CheckOnClick = true;
                cb.Items.AddRange(Enum.GetNames(_type));
                _valueControl = cb;
                _valueType    = VALUE_ENUM_MULTI;
            }
            else
            {
                // Not a bit field, use a normal combo box
                ComboBox cb = new ComboBox();
                cb.DropDownStyle = ComboBoxStyle.DropDownList;
                cb.Items.AddRange(Enum.GetNames(_type));
                cb.SelectedIndex = 0;
                _valueControl    = cb;
                _valueType       = VALUE_ENUM;
            }

            SetEnumValue();
        }
Esempio n. 6
0
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Ctor.");

        try
        {
            FlagsAttribute fa = new FlagsAttribute();

            if (fa == null)
            {
                TestLibrary.TestFramework.LogError("001.1", "Ctor Err !");
                retVal = false;
                return(retVal);
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return(retVal);
    }
Esempio n. 7
0
        private static bool HasFlagsInternal(Type type)
        {
            Contract.Assert(type != null);

            FlagsAttribute attribute = type.GetCustomAttribute <FlagsAttribute>(inherit: false);

            return(attribute != null);
        }
Esempio n. 8
0
        public static bool IsCompositeValue(Type valType)
        {
            FlagsAttribute flagsAttribute = valType.GetCustomAttributes(false).OfType <FlagsAttribute>().SingleOrDefault();

            if (flagsAttribute != null)
            {
                return(true);
            }
            return(false);
        }
        public void AttributesTest()
        {
            SerializableAttribute serializable_attr = new SerializableAttribute();
            FlagsAttribute        flags_attr        = new FlagsAttribute();

            CustomAttributeCollection attr_coll = new CustomAttributeCollection(serializable_attr, flags_attr);

            Attribute [] attributes = attr_coll.GetAttributes();
            Assert.AreEqual(true, attributes != null, "#A0");
            Assert.AreEqual(2, attributes.Length, "#A1");

            // The property is supposed to be giving us the same instance in all the invocations
            Assert.AreSame(attributes, attr_coll.GetAttributes(), "#A2");
        }
Esempio n. 10
0
        public void Execute_4_Dependencies()
        {
            _resolverMock.Resolve <string>().Returns("str-dep-1");
            _resolverMock.Resolve <long>().Returns(42);
            _resolverMock.Resolve <int>().Returns(12);

            var dep4 = new FlagsAttribute();

            _resolverMock.Resolve <FlagsAttribute>().Returns(dep4);

            var queryMock = Substitute.For <IQuery <int, string, long, int, FlagsAttribute> >();

            _queryExecutor.Execute(queryMock);

            queryMock.Received().Execute("str-dep-1", 42, 12, dep4);
        }
		public virtual void  TestFlagsAttribute()
		{
			FlagsAttribute att = new FlagsAttribute();
			Assert.AreEqual(0, att.Flags);
			
			att.Flags = 1234;
			Assert.AreEqual("flags=1234", att.ToString());
			
			FlagsAttribute att2 = (FlagsAttribute) AssertCloneIsEqual(att);
			Assert.AreEqual(1234, att2.Flags);
			
			att2 = (FlagsAttribute) AssertCopyIsEqual(att);
			Assert.AreEqual(1234, att2.Flags);
			
			att.Clear();
			Assert.AreEqual(0, att.Flags);
		}
Esempio n. 12
0
    /// <summary>
    /// 解析枚举
    /// </summary>
    /// <param name="_enumType">枚举类别</param>
    /// <returns>HashCode</returns>
    int OnResolveEnum(Type _enumType)
    {
        int hashCode = _enumType.GetHashCode();

        if (!mEnumPopupValueMaping.ContainsKey(hashCode))
        {
            Dictionary <int, string> vtn = _enumType.ValueToName();
            Dictionary <int, string> vta = _enumType.ValueToAttributeSpecifyValue <AliasTooltipAttribute, string>((a) => { if (a != null)
                                                                                                                           {
                                                                                                                               return(a.alias);
                                                                                                                           }
                                                                                                                           else
                                                                                                                           {
                                                                                                                               return(string.Empty);
                                                                                                                           } });
            List <int>        values = new List <int>(vtn.Keys);
            List <GUIContent> aliass = new List <GUIContent>();
            List <string>     masks  = new List <string>();
            FlagsAttribute    flags  = _enumType.GetFirstAttribute <FlagsAttribute>();

            foreach (int v in values)
            {
                if (string.IsNullOrEmpty(vta[v]))
                {
                    aliass.Add(new GUIContent(vtn[v]));
                }
                else
                {
                    aliass.Add(new GUIContent(vta[v]));
                }
                if (string.IsNullOrEmpty(vta[v]))
                {
                    masks.Add(vtn[v]);
                }
                else
                {
                    masks.Add(vta[v]);
                }
            }
            mEnumPopupValueMaping.Add(hashCode, values.ToArray());
            mEnumPopupAliasMaping.Add(hashCode, aliass.ToArray());
            mEnumPopupMaskAliasMaping.Add(hashCode, masks.ToArray());
            mEnumIsFlagsMaping.Add(hashCode, flags != null);
        }
        return(hashCode);
    }
Esempio n. 13
0
        /// <summary>
        /// Gets a value indicating whether the given <paramref name="type"/> or an expression of this
        /// <see cref="Type"/> is suitable for use in <see cref="GetSelectList(Type)"/> and <see
        /// cref="SelectExtensions.EnumDropDownListFor{TModel,TEnum}(HtmlHelper{TModel}, Expression{Func{TModel, TEnum}})"/>
        /// calls.
        /// </summary>
        /// <param name="type">The <see cref="Type"/> to check.</param>
        /// <returns>
        /// <see langword="true"/> if <see cref="GetSelectList(Type)"/> will not throw when passed given
        /// <see cref="Type"/> and <see
        /// cref="SelectExtensions.EnumDropDownListFor{TModel,TEnum}(HtmlHelper{TModel}, Expression{Func{TModel, TEnum}})"/>
        /// will not throw when passed an expression of this <see cref="Type"/>; <see langword="false"/> otherwise.
        /// </returns>
        /// <remarks>
        /// Currently returns <see langref="true"/> if the <paramref name="type"/> parameter is
        /// non-<see langref="null"/>, is an <see langref="enum"/> type, and does not have a
        /// <see cref="FlagsAttribute"/> attribute.
        /// </remarks>
        public static bool IsValidForEnumHelper(Type type)
        {
            bool isValid = false;

            if (type != null)
            {
                // Type.IsEnum is false for Nullable<T> even if T is an enum.  Check underlying type (if any).
                // Do not support Enum type itself -- IsEnum property is false for that class.
                Type checkedType = Nullable.GetUnderlyingType(type) ?? type;
                if (checkedType.IsEnum)
                {
                    FlagsAttribute attribute = checkedType.GetCustomAttribute <FlagsAttribute>(inherit: false);
                    isValid = attribute == null;
                }
            }

            return(isValid);
        }
        public override string SerializeToJson(object inputObject)
        {
            var            attrList = inputObject.GetType().GetCustomAttributes(false);
            var            listAttr = attrList.ToList();
            FlagsAttribute flagAttr = attrList.Count() != 0 ? (FlagsAttribute)listAttr.Find(item => item.GetType() == typeof(FlagsAttribute)) : null;
            bool           flag     = (flagAttr != null) ? true : false;

            if (flag)
            {
                int value = (int)inputObject;
                return(value.ToString());
            }
            else
            {
                IDictionary <string, object> enumDictionary = BuildJsonDictionary(inputObject);
                object enumValue  = enumDictionary.First().Value;
                string enumstring = "\"" + enumValue.ToString() + "\"";
                return(enumstring);
            }
        }
Esempio n. 15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testFilterTokens() throws Exception
        public virtual void testFilterTokens()
        {
            SnowballFilter             filter     = new SnowballFilter(new TestTokenStream(this), "English");
            CharTermAttribute          termAtt    = filter.getAttribute(typeof(CharTermAttribute));
            OffsetAttribute            offsetAtt  = filter.getAttribute(typeof(OffsetAttribute));
            TypeAttribute              typeAtt    = filter.getAttribute(typeof(TypeAttribute));
            PayloadAttribute           payloadAtt = filter.getAttribute(typeof(PayloadAttribute));
            PositionIncrementAttribute posIncAtt  = filter.getAttribute(typeof(PositionIncrementAttribute));
            FlagsAttribute             flagsAtt   = filter.getAttribute(typeof(FlagsAttribute));

            filter.incrementToken();

            assertEquals("accent", termAtt.ToString());
            assertEquals(2, offsetAtt.startOffset());
            assertEquals(7, offsetAtt.endOffset());
            assertEquals("wrd", typeAtt.type());
            assertEquals(3, posIncAtt.PositionIncrement);
            assertEquals(77, flagsAtt.Flags);
            assertEquals(new BytesRef(new sbyte[] { 0, 1, 2, 3 }), payloadAtt.Payload);
        }
        public ReflectionEnumPropertyInfo(PropertyInfo propertyInfo)
            : base(propertyInfo)
        {
            string[] names  = Enum.GetNames(propertyInfo.PropertyType);
            Array    values = Enum.GetValues(propertyInfo.PropertyType);

            var predefinedValues = new Dictionary <string, T> (names.Length);

            for (int i = 0; i < names.Length; i++)
            {
                predefinedValues.Add(names[i], (T)values.GetValue(i));
            }

            PredefinedValues = predefinedValues;

            FlagsAttribute flags = PropertyInfo.PropertyType.GetCustomAttribute <FlagsAttribute> ();

            if (IsValueCombinable = flags != null)
            {
                DynamicBuilder.RequestOrOperator <T> ();
                DynamicBuilder.RequestHasFlagMethod <T> ();
                DynamicBuilder.RequestCaster <IReadOnlyList <T> > ();
            }
        }
Esempio n. 17
0
        private static void ShowAttributes(MemberInfo attributeTarget)
        {
            Attribute[] attributes = Attribute.GetCustomAttributes(attributeTarget);
            Console.WriteLine("Attributes applied to {0}: {1}",
                              attributeTarget.Name, (attributes.Length == 0 ? "None" : String.Empty));
            foreach (Attribute attribute in attributes)
            {
                // Display the  type of each applied attribute
                Console.WriteLine("  {0}", attribute.GetType().ToString());
                DebuggerDisplayAttribute dda = attribute as DebuggerDisplayAttribute;
                if (dda != null)
                {
                    Console.WriteLine("    Value={0}, Name={1}, Target={2}",
                                      dda.Value, dda.Name, dda.Target);
                }

                FlagsAttribute flags = attribute as FlagsAttribute;
                if (flags != null)
                {
                    Console.WriteLine(flags.ToString());
                    Console.WriteLine(flags.GetType().Name);
                }
            }
        }
Esempio n. 18
0
        public void Execute_6_Dependencies()
        {
            _resolverMock.Resolve <string>().Returns("str-dep-1");
            _resolverMock.Resolve <long>().Returns(42);
            _resolverMock.Resolve <int>().Returns(12);

            var dep4 = new FlagsAttribute();

            _resolverMock.Resolve <FlagsAttribute>().Returns(dep4);

            var dep5 = new SystemException();

            _resolverMock.Resolve <SystemException>().Returns(dep5);

            var dep6 = new TimeSpan();

            _resolverMock.Resolve <TimeSpan>().Returns(dep6);

            var queryMock = Substitute.For <IQuery <int, string, long, int, FlagsAttribute, SystemException, TimeSpan> >();

            _queryExecutor.Execute(queryMock);

            queryMock.Received().Execute("str-dep-1", 42, 12, dep4, dep5, dep6);
        }
 public static void Ctor()
 {
     var attribute = new FlagsAttribute();
 }
        public static object DrawObject(GUIContent title, object obj, Type type, object[] attrs = null)
        {
            using (var lay = new EditorGUILayout.VerticalScope())
            {
                if (null == obj)
                {//初始化
                    obj = TypeUtility.CreateInstance(type);
                }

                float oldLabelWidth = EditorGUIUtility.labelWidth;
                EditorGUIUtility.labelWidth = CalcLabelWidth(title);

                obj = DrawObjectCustom(out bool isDraw, title, obj, type, attrs);
                if (!isDraw)
                {
                    switch (obj)
                    {
                    case float v:
                    {
                        RangeAttribute attr = GetTargetAttr <RangeAttribute>();
                        obj = null == attr?EditorGUILayout.FloatField(title, v) : EditorGUILayout.Slider(title, v, attr.min, attr.max);
                    }
                    break;

                    case double v:
                        obj = EditorGUILayout.DoubleField(title, v);
                        break;

                    case int v:
                    {
                        RangeAttribute attr = GetTargetAttr <RangeAttribute>();
                        obj = null == attr?EditorGUILayout.IntField(title, v) : EditorGUILayout.IntSlider(title, v, (int)attr.min, (int)attr.max);
                    }
                    break;

                    case string v:
                        obj = EditorGUILayout.TextField(title, v);
                        break;

                    case bool v:
                        obj = EditorGUILayout.Toggle(title, v);
                        break;

                    case Vector2 v:
                    {
                        v = EditorGUILayout.Vector2Field(title, v);
                        RangeAttribute attr = GetTargetAttr <RangeAttribute>();
                        if (attr != null)
                        {
                            v.x = Mathf.Clamp(v.x, attr.min, attr.max);
                            v.y = Mathf.Clamp(v.y, attr.min, attr.max);
                            if (v.x > v.y)
                            {
                                v.x = v.y;
                            }

                            using (var lay2 = new EditorGUILayout.HorizontalScope())
                            {
                                GUILayout.Space(EditorGUIUtility.labelWidth);
                                EditorGUILayout.MinMaxSlider(ref v.x, ref v.y, attr.min, attr.max);
                            }
                        }
                        obj = v;
                    }
                    break;

                    case Vector3 v:
                        obj = EditorGUILayout.Vector3Field(title, v);
                        break;

                    case Vector2Int v:
                    {
                        v = EditorGUILayout.Vector2IntField(title, v);
                        RangeAttribute attr = GetTargetAttr <RangeAttribute>();
                        if (attr != null)
                        {
                            Vector2 vf = v;

                            v.x = Mathf.Clamp(Mathf.RoundToInt(vf.x), (int)attr.min, (int)attr.max);
                            v.y = Mathf.Clamp(Mathf.RoundToInt(vf.y), (int)attr.min, (int)attr.max);
                            if (v.x > v.y)
                            {
                                v.x = v.y;
                            }

                            using (var lay2 = new EditorGUILayout.HorizontalScope())
                            {
                                GUILayout.Space(EditorGUIUtility.labelWidth);
                                EditorGUILayout.MinMaxSlider(ref vf.x, ref vf.y, attr.min, attr.max);
                            }

                            v = new Vector2Int((int)vf.x, (int)vf.y);
                        }
                        obj = v;
                    }
                    break;

                    case Vector3Int v:
                        obj = EditorGUILayout.Vector3IntField(title, v);
                        break;

                    case Enum v:
                    {
                        FlagsAttribute attr = GetTargetAttr <FlagsAttribute>();
                        obj = null == attr?EditorGUILayout.EnumPopup(title, v) : EditorGUILayout.EnumFlagsField(title, v);
                    }
                    break;

                    case LayerMask v:
                    {
                        int mask = InternalEditorUtility.LayerMaskToConcatenatedLayersMask(v);
                        mask = EditorGUILayout.MaskField(title, mask, InternalEditorUtility.layers);
                        obj  = InternalEditorUtility.ConcatenatedLayersMaskToLayerMask(mask);
                    }
                    break;

                    case IList v:
                    {
                        if (type.IsGenericType && type.GenericTypeArguments.Length == 1)
                        {
                            Type subType = type.GenericTypeArguments[0];

                            using (var lay2 = new EditorGUILayout.VerticalScope("FrameBox"))
                            {
                                if (subType.IsClass || subType.IsValueType)
                                {
                                    EditorGUIUtility.labelWidth = CalcLabelWidth(title);
                                    EditorGUILayout.BeginHorizontal();
                                    int cnt = EditorGUILayout.IntField(title, v.Count);
                                    if (GUILayout.Button("+", GUILayout.Width(40)))
                                    {
                                        cnt++;
                                        GUI.FocusControl(null);
                                    }
                                    EditorGUILayout.EndHorizontal();
                                    EditorGUIUtility.labelWidth = oldLabelWidth;

                                    int diff = cnt - v.Count;

                                    while (diff < 0)
                                    {
                                        v.RemoveAt(v.Count - 1);
                                        diff++;
                                    }

                                    while (diff > 0)
                                    {
                                        object subObj = TypeUtility.CreateInstance(subType);
                                        v.Add(subObj);
                                        diff--;
                                    }

                                    EditorGUI.indentLevel += 1;
                                    for (int i = 0; i < cnt; i++)
                                    {
                                        using (var lay3 = new EditorGUILayout.VerticalScope("FrameBox"))
                                        {
                                            v[i] = DrawObject(new GUIContent($"{i}"), v[i], subType, attrs);

                                            using (var lay4 = new EditorGUILayout.HorizontalScope())
                                            {
                                                if (GUILayout.Button("↑") && i > 0)
                                                {
                                                    object swap = v[i - 1];
                                                    v[i - 1] = v[i];
                                                    v[i]     = swap;
                                                }
                                                if (GUILayout.Button("↓") && i < cnt - 1)
                                                {
                                                    object swap = v[i + 1];
                                                    v[i + 1] = v[i];
                                                    v[i]     = swap;
                                                }
                                                if (GUILayout.Button("x"))
                                                {
                                                    v.RemoveAt(i);
                                                    i--;
                                                    cnt--;
                                                }
                                            }
                                        }
                                    }
                                    EditorGUI.indentLevel -= 1;
                                }
                            }
                        }
                        else
                        {
                            EditorGUILayout.LabelField($"不支持 {type} 类型");
                        }

                        obj = v;
                    }
                    break;

                    default:
                    {
                        if (!type.IsPrimitive && (type.IsClass || type.IsValueType))
                        {
                            FieldInfo[] fields = type.GetFields();

                            //=============================================================
                            //查找成员显示控制
                            Dictionary <string, bool> enableDict = EnableToggleAttribute.GetEnableDict(obj);
                            //=============================================================

                            int depth = 0;
                            if (title != GUIContent.none)
                            {
                                EditorGUILayout.LabelField($"{title.text}");
                                depth = 1;
                            }

                            EditorGUI.indentLevel += depth;
                            foreach (var field in fields)
                            {
                                //=============================================================
                                if (!EnableToggleItemAttribute.EnableChecker(field, enableDict))
                                {        //不显示
                                    continue;
                                }
                                //===========================================================

                                DrawField(obj, field);
                            }
                            EditorGUI.indentLevel -= depth;
                        }
                        else
                        {
                            EditorGUILayout.LabelField($"不支持 {type} 类型");
                        }
                    }
                    break;
                    }
                }
                EditorGUIUtility.labelWidth = oldLabelWidth;

                return(obj);

                T GetTargetAttr <T>() where T : Attribute
                {
                    T result = null;

                    if (attrs != null)
                    {
                        result = (T)Array.Find(attrs, t => t is T);
                    }

                    if (result == null)
                    {
                        result = type.GetCustomAttribute <T>();
                    }
                    return(result);
                }
            }
        }
Esempio n. 21
0
        public override void  CopyTo(AttributeImpl target)
        {
            FlagsAttribute t = (FlagsAttribute)target;

            t.SetFlags(flags);
        }
Esempio n. 22
0
 override public System.Object Clone()
 {
     FlagsAttribute impl = new FlagsAttribute();
     impl.flags = this.flags;
     return impl;
 }
Esempio n. 23
0
        public static bool HasFlagsInternal(Type type)
        {
            FlagsAttribute attribute = type.GetCustomAttribute <FlagsAttribute>(inherit: false);

            return(attribute != null);
        }
        // [Note by Max 20140906] TODO this should create a new appdomain to import an assembly and then unloading it.
        // If you load an assembly of the current solution you are not able to build anymore
        // since msbuild is unable to delete the assembly because is currently in use.
        private void ImportExternalEnum()
        {
            OpenFileDialog ofd = new OpenFileDialog()
            {
                DefaultExt = "dll",
                Filter     = "Assemblies (*.dll)|*.dll|All Files (*.*)|*.*"
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string   file     = ofd.FileName;
                Assembly assembly = Assembly.LoadFrom(file);

                List <Type> enumTypes = new List <Type>();
                foreach (Type type in assembly.GetExportedTypes())
                {
                    if (type.IsEnum)
                    {
                        enumTypes.Add(type);
                    }
                }

                if (enumTypes.Count == 0)
                {
                    MessageBox.Show("The chosen assembly has no public Enums.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                ConfigurationSectionDesignerDiagram diagram = this.SingleDocumentSelection as ConfigurationSectionDesignerDiagram;
                using (Transaction transaction = diagram.Store.TransactionManager.BeginTransaction("Import External Enum"))
                {
                    using (ImportEnumForm importEnumForm = new ImportEnumForm(enumTypes))
                    {
                        if (importEnumForm.ShowDialog() == DialogResult.OK)
                        {
                            ConfigurationSectionModel model = diagram.ModelElement as ConfigurationSectionModel;

                            Type enumType = importEnumForm.SelectedEnum;

                            FlagsAttribute fa = enumType.GetCustomAttributes(false)
                                                .Where(a => a is FlagsAttribute)
                                                .SingleOrDefault() as FlagsAttribute;

                            EnumeratedType enumeratedType = new EnumeratedType(diagram.Store);
                            enumeratedType.CodeGenOptions = TypeDefinitionCodeGenOptions.None;
                            enumeratedType.Name           = enumType.Name;
                            enumeratedType.Namespace      = enumType.Namespace;
                            enumeratedType.IsFlags        = fa != null;

                            FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
                            foreach (FieldInfo field in fields)
                            {
                                EnumerationLiteral enumeratedLiteral = new EnumerationLiteral(diagram.Store);
                                enumeratedLiteral.Name = field.Name;

                                enumeratedType.Literals.Add(enumeratedLiteral);
                            }

                            model.TypeDefinitions.Add(enumeratedType);
                            transaction.Commit();
                        }
                        else
                        {
                            transaction.Rollback();
                        }
                    }
                }
            }
        }
Esempio n. 25
0
        private static object ConvertData(Type targetType, object value)
        {
            if (value is Array)
            {
                int length = ((Array)value).Length;
                if (length < 1)
                {
                    value = null;
                }
                else if (length == 1)
                {
                    value = ((Array)value).GetValue(0);
                }
            }

            if (value is String)
            {
                value = ((String)value).TrimEnd('\0').Trim();
            }

            if (targetType == null || value == null)
            {
                return(value);
            }

            if (targetType == typeof(DateTime) && value is String)
            {
                DateTime dateTime;
                if (DateTime.TryParseExact((string)value, ExifDecoder.ExifDateTimeFormats,
                                           DateTimeFormatInfo.InvariantInfo,
                                           DateTimeStyles.AllowWhiteSpaces, out dateTime))
                {
                    return(dateTime);
                }
            }

            if (targetType.IsEnum)
            {
                Type underlyingType = Enum.GetUnderlyingType(targetType);
                if (value.GetType() != underlyingType)
                {
                    value = Convert.ChangeType(value, underlyingType);
                }

                if (Enum.IsDefined(targetType, value) || FlagsAttribute.IsDefined(targetType, typeof(FlagsAttribute)))
                {
                    try
                    {
                        return(Enum.ToObject(targetType, value));
                    }
                    catch { }
                }
            }

            if (targetType == typeof(UnicodeEncoding) && value is byte[])
            {
                byte[] bytes = (byte[])value;
                if (bytes.Length <= 1)
                {
                    return(String.Empty);
                }

                return(Encoding.Unicode.GetString(bytes, 0, bytes.Length - 1));
            }

            if (targetType == typeof(Bitmap) && value is byte[])
            {
                byte[] bytes = (byte[])value;
                if (bytes.Length < 1)
                {
                    return(null);
                }

                using (MemoryStream stream = new MemoryStream(bytes))
                {
                    return(Bitmap.FromStream(stream));
                }
            }

            return(value);
        }
Esempio n. 26
0
        private Node CreateLogicalNode(object data, bool writeType, bool useCache)
        {
            Type type = data.GetType();

            Node result = new Node {
                Name = type.Name, Type = type.FullName, WriteType = writeType
            };

            if (WriteCache.ContainsKey(data))
            {
                if (useCache)
                {
                    return(WriteCache[data]);
                }

                if (WriteCache[data].RefID == 0)
                {
                    Increment++;
                    WriteCache[data].RefID = Increment;
                }

                result.WriteType = false;
                result.Reference = WriteCache[data].RefID;
                return(result);
            }
            else
            {
                WriteCache.Add(data, result);
            }

            PropertyInfo[] properties = Reflector.GetProperties(type);// type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            if (properties.Length < 1)
            {
                result.Value = data.ToString();
            }

            foreach (PropertyInfo info in properties)
            {
                if (info.IsDefined(typeof(XmlIgnoreAttribute), true))
                {
                    continue;
                }
                if (!info.CanRead)
                {
                    continue;
                }
                if (!info.CanWrite)
                {
                    continue;
                }
                if (info.GetSetMethod() == null)
                {
                    continue;
                }

                object value = info.GetValue(data, null);
                if (value == null)
                {
                    continue;
                }

                // check vs. default value
                object[] attributes = info.GetCustomAttributes(typeof(DefaultValueAttribute), true);
                if (attributes.Length > 0)
                {
                    DefaultValueAttribute def = attributes[0] as DefaultValueAttribute;
                    if (def.Value != null)
                    {
                        if (def.Value.Equals(value))
                        {
                            continue;
                        }
                    }
                }

                Type valueType = value.GetType();

                if (info.PropertyType.IsPrimitive || info.PropertyType == typeof(string) || info.PropertyType.IsEnum)
                {
                    FlagsAttribute flags = Reflector.GetAttribute <FlagsAttribute>(info.PropertyType);

                    if (flags != null)
                    {
                        Node sub = new Node {
                            Name = info.Name, Value = ((int)value).ToString()
                        };
                        result.Nodes.Add(sub);
                    }
                    else
                    {
                        Node sub = new Node {
                            Name = info.Name, Value = value.ToString()
                        };
                        result.Nodes.Add(sub);
                    }
                }
                else if (valueType.IsValueType)
                {
                    TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(valueType);
                    if (converter != null)
                    {
                        try
                        {
                            string str = converter.ConvertToString(value);
                            Node   sub = new Node {
                                Name = info.Name, Value = str
                            };
                            result.Nodes.Add(sub);
                        }
                        catch (Exception exc)
                        {
                            throw exc;
                        }
                    }
                    else
                    {
                        Node sub = CreateLogicalNode(value, !info.PropertyType.FullName.Equals(valueType.FullName), false);
                        sub.Name = info.Name;
                        result.Nodes.Add(sub);
                    }
                }
                else if (value is IList)
                {
                    Node sub = new Node {
                        Name = info.Name, Type = valueType.FullName
                    };
                    result.Nodes.Add(sub);

                    string name     = null;
                    string fullname = null;

                    if (valueType.IsGenericType || valueType.BaseType.IsGenericType)
                    {
                        Type t = valueType.IsGenericType ? valueType : valueType.BaseType;

                        Type[] gens = t.GetGenericArguments();
                        if (gens.Length > 0)
                        {
                            name     = gens[0].Name;
                            fullname = gens[0].FullName;
                        }
                    }
                    else
                    {
                        fullname = ((IList)value)[0].GetType().FullName;
                    }

                    foreach (object item in ((IList)value))
                    {
                        if (item != null)
                        {
                            Type stype = item.GetType();
                            Node child = CreateLogicalNode(item, !fullname.Equals(item.GetType().FullName), false);

                            if (!string.IsNullOrEmpty(name))
                            {
                                child.Name = name;
                            }

                            sub.Nodes.Add(child);
                        }
                        else
                        {
                            Node child = new Node {
                                Name = name
                            };
                            sub.Nodes.Add(child);
                        }
                    }
                }
                else if (value is IDictionary)
                {
                    Node sub = new Node {
                        Name = info.Name, Type = valueType.FullName
                    };
                    result.Nodes.Add(sub);

                    Type itemType = null;

                    if (valueType.IsGenericType)
                    {
                        Type[] gens = valueType.GetGenericArguments();
                        if (gens.Length > 0)
                        {
                            itemType = gens[1];
                        }
                    }
                    else if (valueType.BaseType.IsGenericType)
                    {
                        Type[] gens = valueType.BaseType.GetGenericArguments();
                        if (gens.Length > 0)
                        {
                            itemType = gens[1];
                        }
                    }

                    IDictionary dict = (IDictionary)value;

                    foreach (object key in dict.Keys)
                    {
                        Node element = CreateLogicalNode(dict[key], true, false);
                        //Node element = CreateLogicalNode(dict[key], !dict[key].GetType().FullName.Equals(itemType.FullName), false);
                        element.Key = key.ToString();
                        sub.Nodes.Add(element);
                    }
                }
                //else if (value is Entity)// && info.GetAttribute<NoRefAttribute>() == null)
                //{
                //    // entity as a property - we want a reference here, not the actual entity
                //    Node sub = new Node { Name = info.Name, WriteType = false };

                //    if (WriteCache.ContainsKey(value))
                //        sub.Reference = WriteCache[value].RefID;
                //    else
                //    {
                //        Node cached = CreateNode(value, false, false);

                //        if (WriteCache[value].RefID == 0)
                //        {
                //            Increment++;
                //            WriteCache[value].RefID = Increment;
                //        }

                //        sub.Reference = cached.RefID;
                //    }

                //    result.Nodes.Add(sub);
                //}
                else
                {
                    Node sub = CreateLogicalNode(value, !info.PropertyType.FullName.Equals(valueType.FullName), false);
                    sub.Name = info.Name;
                    result.Nodes.Add(sub);
                }
            }

            if (data is Control)
            {
                //    Entity entity = data as Entity;

                //    if (!entity.IsPrototype)
                //    {
                //        Node sub = new Node { Name = "Components", Type = typeof(Component).FullName };
                //        result.Nodes.Add(sub);

                //        foreach (Component c in entity.Components)
                //        {
                //            Node child = CreateNode(c, true, false, resources);
                //            child.Name = "Component";
                //            sub.Nodes.Add(child);
                //        }

                ElementCollection elements = ((Control)data).GetElements();

                if (elements.Count > 0)
                {
                    Node sub = new Node {
                        Name = "Elements", Type = typeof(Control).FullName
                    };
                    result.Nodes.Add(sub);

                    foreach (Control e in elements)
                    {
                        sub.Nodes.Add(CreateLogicalNode(e, false, true));
                    }
                }
                //    }
                //    else
                //    {
                //        Node sub = new Node { Name = "Components", Type = typeof(Component).FullName };
                //        result.Nodes.Add(sub);
                //        Node child = CreateNode(entity.Transform, true, false, resources);
                //        child.Name = "Component";
                //        sub.Nodes.Add(child);
                //    }
            }

            return(result);
        }