Beispiel #1
0
 public void ListMethods_ShouldReturnOverLoadedInterfaceMethods()
 {
     MethodInfo[] methods = typeof(IEnumerable <string>).ListMethods().ToArray();
     Assert.That(methods.Length, Is.EqualTo(2));
     Assert.That(methods.Contains((MethodInfo)MemberInfoExtensions.ExtractFrom <IEnumerable <string> >(i => i.GetEnumerator())));
     Assert.That(methods.Contains((MethodInfo)MemberInfoExtensions.ExtractFrom <IEnumerable>(i => i.GetEnumerator())));
 }
        public void GetAttribute_memeberInfo_false()
        {
            Type            t      = typeof(MyBaseTestClass);
            MyTestAttribute actual = MemberInfoExtensions.GetAttribute <MyTestAttribute>(t, false);

            Assert.IsNotNull(actual);
        }
Beispiel #3
0
 public void ListProperties_ShouldReturnOverLoadedInterfaceProperties()
 {
     PropertyInfo[] properties = typeof(IEnumerator <string>).ListProperties().ToArray();
     Assert.That(properties.Length, Is.EqualTo(2));
     Assert.That(properties.Contains((PropertyInfo)MemberInfoExtensions.ExtractFrom <IEnumerator <string> >(i => i.Current)));
     Assert.That(properties.Contains((PropertyInfo)MemberInfoExtensions.ExtractFrom <IEnumerator>(i => i.Current)));
 }
        public void IsAttributeDefined_memberInfo_inherit_false()
        {
            Type t      = typeof(MyDerivedTestClass);
            bool actual = MemberInfoExtensions.IsAttributeDefined <MyTestAttribute>(t, false);

            Assert.IsFalse(actual);
        }
Beispiel #5
0
        /// <summary>
        /// Does the opposite: creates a literal string from values
        /// </summary>
        private void UpdateMember()
        {
            //var pairs = from kvp in dictionary orderby kvp.Value select kvp;//按值排序,在这里忽略,因为不会使用本方法
            //var pairs = dictionary.
            int currentValue = 1;
            var keyValues    = new List <string>();

            foreach (var pair in dictionary)
            {
                string keyValue;
                if (pair.Value == currentValue)
                {
                    keyValue = pair.Key;
                }
                else
                {
                    currentValue = pair.Value;
                    keyValue     = string.Format("{0}={1}", pair.Key, pair.Value);
                }
                keyValues.Add(keyValue);
                currentValue++;
            }
            string literalType = string.IsNullOrEmpty(Name) ? "enum" : Name;

            literalType += " ";
            literalType += string.Join(", ", keyValues.ToArray());
            MemberInfoExtensions.SetMemberValue(memberInfo, owner, literalType);
        }
        public void IsAttributeDefined_memberInfo_using_base_attribute()
        {
            Type t      = typeof(MyBaseTestClass);
            bool actual = MemberInfoExtensions.IsAttributeDefined <Attribute>(t);

            Assert.IsTrue(actual);
        }
        public void GetAttribute_on_inherited_true()
        {
            Type            t      = typeof(MyDerivedTestClass);
            MyTestAttribute actual = MemberInfoExtensions.GetAttribute <MyTestAttribute>(t, true);

            Assert.IsNotNull(actual);
        }
Beispiel #8
0
        public void ListMethods_ShouldReturnMethodsFromTheWholeHierarchy()
        {
            MethodInfo[] methods = typeof(IGrandChild).ListMethods().ToArray();

            Assert.That(methods.Length, Is.EqualTo(3));
            Assert.That(methods.Contains((MethodInfo)MemberInfoExtensions.ExtractFrom <IParent>(i => i.Foo())));
            Assert.That(methods.Contains((MethodInfo)MemberInfoExtensions.ExtractFrom <IChild>(i => i.Bar())));
            Assert.That(methods.Contains((MethodInfo)MemberInfoExtensions.ExtractFrom <IGrandChild>(i => i.Baz())));
        }
        public void GetAttributes_memberInfo_inherit_false()
        {
            Type t = typeof(MyDerivedTestClass);

            MyTestAttribute[] actual = MemberInfoExtensions.GetAttributes <MyTestAttribute>(t, false);

            Assert.IsNotNull(actual);
            Assert.AreEqual <int>(0, actual.Length);
        }
Beispiel #10
0
        internal EnumType(object owner, MemberInfo memberInfo)
        {
            this.owner      = owner;
            this.memberInfo = memberInfo;
            string name;

            Extract((string)MemberInfoExtensions.GetMemberValue(memberInfo, owner), out name, out dictionary);
            Name = name;
        }
        public void GetAttributes_memberInfo()
        {
            Type t = typeof(MyBaseTestClass);

            MyTestAttribute[] actual = MemberInfoExtensions.GetAttributes <MyTestAttribute>(t);

            Assert.IsNotNull(actual);
            Assert.AreEqual <int>(1, actual.Length);
            Assert.IsNotNull(actual[0]);
        }
Beispiel #12
0
        /// <summary>
        /// Determines whether or not 'member' should be visible in the inspector
        /// The logic goes like this:
        /// If member was a method or property it is visible only if it's annotated with [Show]
        /// If member was a field it is visible if
        /// 1- it's annotated with [Show]
        /// 2- OR if it's serializable
        /// </summary>
        public static bool IsVisibleMember(MemberInfo member)
        {
            if (member is MethodInfo)
            {
                return(Attributes.Show.Any((t) => MemberInfoExtensions.IsDefined(member, t)));
            }

            var field = member as FieldInfo;

            if (field != null)
            {
                if (Attributes.Hide.Any((t) => MemberInfoExtensions.IsDefined(field, t)))
                {
                    return(false);
                }

                if (Attributes.Show.Any((t) => MemberInfoExtensions.IsDefined(field, t)))
                {
                    return(true);
                }

                if (field.IsDefined <SerializeField>())
                {
                    return(true);
                }

                return(IsSerializableField(field));
            }

            var property = member as PropertyInfo;

            if (property == null || Attributes.Hide.Any((t) => MemberInfoExtensions.IsDefined(property, t)))
            {
                return(false);
            }

            // accept properties such as transform.position, rigidbody.mass, etc
            // exposing unity properties is useful when inlining objects via [Inline]
            // (which is the only use-case these couple of lines are meant for)
            var  declType         = property.DeclaringType;
            bool isValidUnityType = declType.IsA <Component>() && !declType.IsA <MonoBehaviour>();
            bool unityProp        = isValidUnityType && property.CanReadWrite() && !IgnoredUnityProperties.Contains(property.Name);

            if (unityProp)
            {
                return(true);
            }

            if (Attributes.Show.Any((t) => MemberInfoExtensions.IsDefined(property, t)))
            {
                return(true);
            }

            return(false);
        }
Beispiel #13
0
        /// <summary>
        /// Creates a new <see cref="MethodContext"/> instance.
        /// </summary>
        /// <remarks>Calling this constructor is time consuming operation. It is strongly advised to cache the created instances.</remarks>
        public MethodContext(Func <object, object?[], object?> dispatch)
        {
            if (dispatch is null)
            {
                throw new ArgumentNullException(nameof(dispatch));
            }

            ExtendedMemberInfo memberInfo = MemberInfoExtensions.ExtractFrom(dispatch);

            Member   = memberInfo.Member;
            Method   = memberInfo.Method;
            Dispatch = dispatch;
        }
Beispiel #14
0
 /// <summary>Get benchmark types defined in the assembly.</summary>
 /// <param name="assembly">The assembly to get benchmarks from.</param>
 /// <returns>Benchmark types from the assembly</returns>
 public static Type[] GetBenchmarkTypes([NotNull] Assembly assembly) =>
 // Use reflection for a more maintainable way of creating the benchmark switcher,
 // Benchmarks are listed in namespace order first (e.g. BenchmarkDotNet.Samples.CPU,
 // BenchmarkDotNet.Samples.IL, etc) then by name, so the output is easy to understand.
 assembly
 .GetTypes()
 .Where(
     t =>
     t.GetMethods(BindingFlags.Instance | BindingFlags.Public)
     .Any(m => MemberInfoExtensions.GetCustomAttributes <BenchmarkAttribute>(m, true).Any()))
 .Where(t => !t.IsGenericType && !t.IsAbstract)
 .OrderBy(t => t.Namespace)
 .ThenBy(t => t.Name)
 .ToArray();
        public static string GetPropertyDisplayName(MemberInfo property, bool splitCamelCase = true)
        {
            var displayNameAttribute = MemberInfoExtensions.GetCustomAttribute <DisplayNameAttribute>(property, true);

            if (displayNameAttribute != null)
            {
                return(displayNameAttribute.DisplayName);
            }

#if NET45 || NET46 || NETSTANDARD2_1
            var displayAttribute = MemberInfoExtensions.GetCustomAttribute <System.ComponentModel.DataAnnotations.DisplayAttribute>(property, true);
            if (displayAttribute != null)
            {
                return(displayAttribute.Name);
            }
#endif
            //well, no attribute found, let's just take that property's name then...
            return(splitCamelCase ? SplitCamelCase(property.Name) : property.Name);
        }
Beispiel #16
0
        public static float GetMemberDisplayOrder(MemberInfo member)
        {
            var attribute = MemberInfoExtensions.GetCustomAttribute <DisplayAttribute>(member);

            if (attribute != null && attribute.DisplayOrder.HasValue)
            {
                return(attribute.Order);
            }

            switch (member.MemberType)
            {
            case MemberTypes.Field: return(100f);

            case MemberTypes.Property: return(200f);

            case MemberTypes.Method: return(300f);

            default: throw new NotSupportedException();
            }
        }
        private static OptionTypeRegistrationAttribute GetRegistrationAttribute(Type type)
        {
            IEnumerable <OptionTypeRegistrationAttribute> source = Enumerable.Where <OptionTypeRegistrationAttribute>(MemberInfoExtensions.GetCustomAttributes <OptionTypeRegistrationAttribute>((MemberInfo)type, false), (Func <OptionTypeRegistrationAttribute, bool>)(attribute => attribute.OptionTypeType == typeof(TOptionType)));

            if (!Enumerable.Any <OptionTypeRegistrationAttribute>(source))
            {
                return((OptionTypeRegistrationAttribute)null);
            }
            return(Enumerable.First <OptionTypeRegistrationAttribute>(source));
        }
Beispiel #18
0
        public static bool IsVisible(MemberInfo member, object target)
        {
            MethodCaller <object, bool> isVisible;

            if (!_isVisibleCache.TryGetValue(member, out isVisible))
            {
                //Debug.Log("Building delegate for conditionally visible member: " + member.Name);

                var attr = MemberInfoExtensions.GetCustomAttribute <VisibleWhenAttribute>(member);
                if (attr == null)
                {
                    _isVisibleCache[member] = AlwaysVisible;
                    return(true);
                }

                var targetType           = target.GetType();
                var conditionMemberNames = attr.ConditionMembers;
                var conditions           = new List <MethodCaller <object, bool> >(conditionMemberNames.Length);

                for (int i = 0; i < conditionMemberNames.Length; i++)
                {
                    var conditionMemberName = conditionMemberNames[i];

                    if (string.IsNullOrEmpty(conditionMemberName))
                    {
                        Debug.Log("Empty condition is used in VisibleWhen annotated on member: " + member.Name);
                        continue;
                    }

                    bool negate = conditionMemberName[0] == '!';
                    if (negate)
                    {
                        conditionMemberName = conditionMemberName.Remove(0, 1);
                    }

                    var conditionMember = targetType.GetMemberFromAll(conditionMemberName, Flags.StaticInstanceAnyVisibility);
                    if (conditionMember == null)
                    {
                        Debug.Log("Member not found: " + conditionMemberName);
                        _isVisibleCache[conditionMember] = AlwaysVisible;
                        return(true);
                    }

                    Assert.IsTrue(attr.Operator == '|' || attr.Operator == '&',
                                  "Only AND ('&') and OR ('|') operators are supported");

                    MethodCaller <object, bool> condition = null;
                    switch (conditionMember.MemberType)
                    {
                    case MemberTypes.Field:
                        // I feel like there should be a shorter way of doing this...
                        if (negate)
                        {
                            condition = (x, y) => !(bool)(conditionMember as FieldInfo).GetValue(x);
                        }
                        else
                        {
                            condition = (x, y) => (bool)(conditionMember as FieldInfo).GetValue(x);
                        }
                        break;

                    case MemberTypes.Property:
                        if (negate)
                        {
                            condition = (x, y) => !(bool)(conditionMember as PropertyInfo).GetValue(x, null);
                        }
                        else
                        {
                            condition = (x, y) => (bool)(conditionMember as PropertyInfo).GetValue(x, null);
                        }
                        break;

                    case MemberTypes.Method:
                        if (negate)
                        {
                            condition = (x, y) => !(bool)(conditionMember as MethodInfo).Invoke(x, y);
                        }
                        else
                        {
                            condition = (x, y) => (bool)(conditionMember as MethodInfo).Invoke(x, y);
                        }
                        break;
                    }

                    Assert.IsNotNull(condition, "Should have assigned a condition by now for member type: " + conditionMember.MemberType);
                    conditions.Add(condition);
                }

                isVisible = (tgt, args) =>
                {
                    bool ret = attr.Operator == '&';
                    for (int i = 0; i < conditions.Count; i++)
                    {
                        var condition = conditions[i];
                        if (attr.Operator == '&')
                        {
                            ret &= condition(tgt, args);
                        }
                        else
                        {
                            ret |= condition(tgt, args);
                        }
                    }
                    return(ret);
                };

                //TODO: Fix FastReflection bug generating methods when target is 'object'
                //isVisible = method.DelegateForCall<object, bool>();
                //FastReflection.GenDebugAssembly("IsVisible_" + method.Name + ".dll", null, null, method, null, null);

                _isVisibleCache[member] = isVisible;
            }

            var result = isVisible(target, null);

            return(result);
        }
Beispiel #19
0
 protected void SetValue(IEnumerable value)
 {
     MemberInfoExtensions.SetMemberValue(memberInfo, owner, value);
 }
Beispiel #20
0
 protected System.Type GetValueType()
 {
     return(MemberInfoExtensions.GetMemberType(memberInfo));
 }
Beispiel #21
0
 protected IEnumerable GetValue()
 {
     return((IEnumerable)MemberInfoExtensions.GetMemberValue(memberInfo, owner));
 }
 public void GetAttribute_null_memberInfo_false()
 {
     MemberInfoExtensions.GetAttribute <MyTestAttribute>(null, true);
 }
 public void GetAttributes_null_memberInfo()
 {
     MemberInfoExtensions.GetAttributes <MyTestAttribute>(null);
 }
Beispiel #24
0
        public void Initialize(MethodInfo method, object rawTarget, UnityObject unityTarget, int id, BaseGUI gui, EditorRecord prefs)
        {
            this.prefs       = prefs;
            this.gui         = gui;
            this.rawTarget   = rawTarget;
            this.unityTarget = unityTarget;
            this.id          = id;

            if (initialized)
            {
                return;
            }
            initialized = true;

            isCoroutine = method.ReturnType == typeof(IEnumerator);

            var commentAttr = MemberInfoExtensions.GetCustomAttribute <CommentAttribute>(method);

            if (commentAttr != null)
            {
                comment = commentAttr.comment;
            }

            niceName = method.GetNiceName();

            if (niceName.IsPrefix("dbg") || niceName.IsPrefix("Dbg"))
            {
                niceName = niceName.Remove(0, 3);
            }

            invoke = method.DelegateForCall();
            var argInfos = method.GetParameters();
            int len      = argInfos.Length;

            argValues  = new object[len];
            argKeys    = new int[len];
            argMembers = new EditorMember[len];

            for (int iLoop = 0; iLoop < len; iLoop++)
            {
                int i       = iLoop;
                var argInfo = argInfos[i];

                argKeys[i] = RuntimeHelper.CombineHashCodes(id, argInfo.ParameterType.Name + argInfo.Name);

                argValues[i] = TryLoad(argInfos[i].ParameterType, argKeys[i]);

                argMembers[i] = EditorMember.WrapGetSet(
                    @get: () => argValues[i],
                    @set: x => argValues[i] = x,
                    @rawTarget: rawTarget,
                    @unityTarget: unityTarget,
                    @attributes: argInfo.GetCustomAttributes(true) as Attribute[],
                    @name: argInfo.Name,
                    @id: argKeys[i],
                    @dataType: argInfo.ParameterType
                    );
            }

#if DBG
            Log("Method drawer init");
#endif
        }
 public void IsAttributeDefined_null_memberInfo_true()
 {
     MemberInfoExtensions.IsAttributeDefined <MyTestAttribute>(null, true);
 }
Beispiel #26
0
        public CategoryDefinitionResolver()
        {
            _excluded = new MembersList();

            // member resolver (when including members to a certain category via attributes)
            _memres = (input, def) =>
            {
                var output = new MembersList();
                output.AddRange(input.Where(m =>
                {
                    var caetgory = MemberInfoExtensions.GetCustomAttribute <CategoryAttribute>(m);
                    if (caetgory != null && caetgory.name == def.FullPath)
                    {
                        return(true);
                    }
                    var show = MemberInfoExtensions.GetCustomAttribute <ShowAttribute>(m);
                    return(show != null && show.Category == def.FullPath);
                }));
                return(output);
            };

            _defres = new Func <MembersList, DefineCategoryAttribute, MembersList>[]
            {
                // regex pattern resolver
                (input, def) =>
                {
                    var output  = new MembersList();
                    var pattern = def.Pattern;
                    if (!pattern.IsNullOrEmpty())
                    {
                        output.AddRange(input.Where(member => Regex.IsMatch(member.Name, pattern)));
                    }
                    return(output);
                },

                // return type resolver
                (input, def) =>
                {
                    var output     = new MembersList();
                    var returnType = def.DataType;
                    if (returnType != null)
                    {
                        output.AddRange(input.Where(m => m.GetDataType().IsA(returnType)));
                    }
                    return(output);
                },

                // member type resolver
                (input, def) =>
                {
                    var output = new MembersList();
                    Predicate <CategoryMemberType> isMemberTypeDefined = mType => (def.MemberType & mType) > 0;
                    output.AddRange(input.Where(m => isMemberTypeDefined((CategoryMemberType)m.MemberType)));
                    return(output);
                },

                // explicit members resolver
                (input, def) =>
                {
                    var output          = new MembersList();
                    var explicitMembers = def.ExplicitMembers;
                    output.AddRange(input.Where(m => explicitMembers.Contains(m.Name)));
                    return(output);
                },
            };
        }
Beispiel #27
0
 private static Dictionary <DnsType, DnsResourceData> InitializePrototypes()
 {
     return(Enumerable.ToDictionary(Enumerable.Select(Enumerable.Where(Enumerable.SelectMany((IEnumerable <Type>)Assembly.GetExecutingAssembly().GetTypes(), (Func <Type, IEnumerable <DnsTypeRegistrationAttribute> >)(type => MemberInfoExtensions.GetCustomAttributes <DnsTypeRegistrationAttribute>((MemberInfo)type, false)), (type, attribute) => new
     {
         type = type,
         attribute = attribute
     }), param0 => typeof(DnsResourceData).IsAssignableFrom(param0.type)), param0 => new
     {
         Type = param0.attribute.Type,
         Prototype = (DnsResourceData)Activator.CreateInstance(param0.type, true)
     }), prototype => prototype.Type, prototype => prototype.Prototype));
 }
 public void ThrowsArgumentNullException_WhenMemberInfoIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => MemberInfoExtensions.GetNameUsingJsonProperty(null));
 }
Beispiel #29
0
 public void WhenIsNull_ThenThrowException()
 {
     Assert.Throws <ArgumentNullException>(() => MemberInfoExtensions.GetAttribute <UsedMethodAttribute>(null));
 }
 public void GetCustomAttributesNullTest()
 {
     Assert.IsNotNull(MemberInfoExtensions.GetCustomAttributes <Attribute>(null, true));
     Assert.Fail();
 }