Attribute 的介绍

      最近帮同事搞了一个小实验。真是简单易懂,把它记下来。保不齐以后会用来做些代码生成的事儿。

1。 声明Attribute

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
    public sealed class ICEClassAttribute : Attribute
    {
        public ICEClassAttribute( )
        {
        }
    }

    [AttributeUsage(AttributeTargets.Interface, Inherited = false, AllowMultiple = true)]
    public sealed class ICEInterfaceAttribute : Attribute
    {
        public ICEInterfaceAttribute()
        {
        }

    }

 

2。 使用特性标记类。

[ICEAttribute.ICEClass]
  public class Product
  {
      public int ID { get; set; }

      public string Name { get; set; }
  }
  [ICEAttribute.ICEInterface]
  public interface ISell
  {
      List<Product> Show();

      Product ShowOne(int id);
  }

 

3。 反射程序集,对标记类进行代码生成。

Assembly cur  = Assembly.LoadFile(fileName);
            //object[] classList = cur.GetCustomAttributes(typeof(ICEClassAttribute), false);
            Type[] classList =cur.GetTypes();
            foreach (var item in classList)
            {
                var t =  item;
                bool has = false;
                foreach (Attribute attr in
                    t.GetCustomAttributes(false))
                {
                    if(attr.GetType()== typeof(ICEClassAttribute))
                    {
                        has = true;
                    }
                }
                if (has)
                {
                    message += "类型" + t.Name + "\n";
                    foreach (var p in t.GetProperties())
                    {
                        message += " 名称 " + p.Name + " 类型 " + p.PropertyType.Name + "\n";
                    }
                    message += " \n";
                }

                has = false;
                foreach (Attribute attr in
                    t.GetCustomAttributes(false))
                {
                    if (attr.GetType() == typeof(ICEAttribute.ICEInterfaceAttribute))
                    {
                        has = true;
                    }
                }
                if (has)
                {
                    message += "接口" + t.Name + "\n";
                    foreach (var p in t.GetMethods())
                    {
                        message += " 名称 " + p.Name;
                        foreach (var pp in p.GetParameters())
                        {
                            message += " 参数 " + p.Name + " 类型" + pp.Name + "\n";
                        }
                        message += " 返回类型 " + p.ReturnType.Name + "\n";
                    }
                    message += " \n";
                }
            }

你可能感兴趣的:(attribute)