Пример #1
0
        public static void Demo7()
        {
            Person person = new Person {
                Name = "TT", Age = 20
            };
            Type                 type                 = person.GetType();
            PropertyInfo         propertyInfo         = type.GetProperty("Age");
            ValidateAgeAttribute validateAgeAttribute = (ValidateAgeAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ValidateAgeAttribute));

            Console.WriteLine("允许的最大年龄:" + validateAgeAttribute.MaxAge);
            validateAgeAttribute.Validate(person.Age);
            Console.WriteLine(validateAgeAttribute.ValidateResult);
        }
Пример #2
0
        public static void AttributeDemo3()
        {
            Type       tp         = typeof(MyTester);
            MemberInfo memberInfo = tp.GetMethod("CannotRun");
            var        myAtt      = (TestAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(TestAttribute));

            myAtt.RunTest();

            MyTester tester = new MyTester {
                Age = 10
            };
            Type                 type                 = tester.GetType();
            PropertyInfo         propertyInfo         = type.GetProperty("Age");
            ValidateAgeAttribute validateAgeAttribute = (ValidateAgeAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ValidateAgeAttribute));

            Console.WriteLine(validateAgeAttribute.MaxAge);
            validateAgeAttribute.IsRight(tester.Age);
        }