• 一段关于测试和自定义Attribute的代码


    来自《西夏普入门经典》

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace ConsoleApplication1
    {
    
        [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
        public class XXXAttribute : Attribute
        {
            public XXXAttribute(System.Type testCase)
            {
                TestCase = testCase;
            }
    
            public readonly System.Type TestCase;
    
            public void Test()
            {
                object o = Activator.CreateInstance(TestCase);
            }
        }
    
        public class TestAnObject
        {
            public TestAnObject()
            {
                SomeCodeOrOther scooby = new SomeCodeOrOther();
                if (scooby.Do() != 999)
                    throw new Exception("Pesky Kids");
            }
        }
    
        [XXX(typeof(TestAnObject))]
        public class SomeCodeOrOther
        {
            public SomeCodeOrOther()
            {
    
            }
    
            public int Do()
            {
                return 999;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
    
                Assembly A = Assembly.GetExecutingAssembly();
                System.Type[] types = A.GetExportedTypes();
    
                foreach (System.Type t in types)
                {
                    Console.WriteLine("Checking type {0}", t.ToString());
    
                    object[] atts = t.GetCustomAttributes(typeof(XXXAttribute), false);
    
                    if (atts.Length == 1)
                    {
                        Console.WriteLine("  Found XXXAttribute: Running Test");
                        XXXAttribute tca = atts[0] as XXXAttribute;
    
                        try
                        {
                            tca.Test();
                            Console.WriteLine("PASSED");
                        }
                        catch (System.Exception ex)
                        {
                            Console.WriteLine("FAILED");
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
    
                Console.Read();
            }
        }
    }
  • 相关阅读:
    疫苗玻璃瓶行业,能发生国产替代吗
    马斯克是如何借力打力的?
    什么是分析立体主义
    这5家公司代表了高瓴资本眼中的科技产业未来
    玻尿酸之王华熙生物,为什么要做食品和饮料(下)
    ajax缺点
    babel转码器
    docker 缺陷
    MVVM中的vm双向监听和mvc的缺点
    mybatisPlus中的模糊查询问题
  • 原文地址:https://www.cnblogs.com/mumuliang/p/3896762.html
Copyright © 2020-2023  润新知