コード例 #1
0
        public void TestGetTypeParamConstraints()
        {
            Type gcClass = typeof(GenericConstrainedClass <, , ,>);

            Type[] typeparams = gcClass.GetGenericArguments();

            Type tParam = typeparams[0];
            Type uParam = typeparams[1];
            Type vParam = typeparams[2];
            Type wParam = typeparams[3];

            var tExpected = new TypeConstraint[] { TypeConstraint.Struct };
            var uExpected = new TypeConstraint[] { TypeConstraint.Class, TypeConstraint.Ctor };
            var vExpected = new TypeConstraint[] { TypeConstraint.TypeParam(3) };
            var wExpected = new TypeConstraint[] { TypeConstraint.Type(new MemberRef("", MemberRefType.Class, typeof(TestClass).MetadataToken)) };

            AssertTypeConstraints(tExpected, utility.GetTypeParamConstraints(tParam));
            AssertTypeConstraints(uExpected, utility.GetTypeParamConstraints(uParam));
            AssertTypeConstraints(vExpected, utility.GetTypeParamConstraints(vParam));
            AssertTypeConstraints(wExpected, utility.GetTypeParamConstraints(wParam));
        }
コード例 #2
0
        public IReadOnlyList <TypeConstraint> GetTypeParamConstraints(Type typeParam)
        {
            Check.Ref(typeParam);
            Check.Cond(typeParam.IsGenericParameter, "typeParam must be a generic parameter type");

            List <TypeConstraint> constraints = new List <TypeConstraint>();
            var attr = typeParam.GenericParameterAttributes;

            if (attr.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint))
            {
                constraints.Add(TypeConstraint.Struct);
            }
            else
            {
                if (attr.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint))
                {
                    constraints.Add(TypeConstraint.Class);
                }
                if (attr.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint))
                {
                    constraints.Add(TypeConstraint.Ctor);
                }

                foreach (var constraint in typeParam.GetGenericParameterConstraints())
                {
                    if (constraint.IsGenericParameter)
                    {
                        int pos = constraint.GenericParameterPosition;
                        constraints.Add(TypeConstraint.TypeParam(pos));
                    }
                    else
                    {
                        MemberRef mRef = new MemberRef(constraint.Name, GetMemberRefType(constraint), constraint.MetadataToken);
                        constraints.Add(TypeConstraint.Type(mRef));
                    }
                }
            }

            return(constraints.ToArray());
        }