zoukankan      html  css  js  c++  java
  • C#特性

    特性是一个类,需要继承或间接继承System.Attribute。

    1.常见的特性

      AttributeUsage:定义特性定义到目标元素。

      Flags:将枚举值作为位标记,而非数值。

            [Flags]
            public enum Animal
            {
                Dog = 0x0001,
                Cat = 0x0002,
                Chicken = 0x0004,
                Duck = 0x0008
            }   
        
            Animal animal = Animal.Dog| Animal.Cat;
          WriteLine(animal.ToString());//Animal使用Flags特性,输出Dog,Cat;不使用Flags特性,输出3     

      DllImport:调用非托管代码。

        public class DllImportDemo
        {
            [DllImport("User32.dll")]
            public static extern int MessageBox(int hParent, string msg, string caption, int type);
            public static int Main()
            {
                return MessageBox(0, "使用特性", ".NET Attribute", 0);
            }
        }
    
        //调用
        DllImportDemo.Main();

    2.尝试自己写一个特性

        [AttributeUsage(AttributeTargets.Property,  //应用于属性
            AllowMultiple = false,                  //不允许应用多次
            Inherited = false)]                     //不继承到派生类
        public class TrimAttribute : System.Attribute
        {
            public Type Type { get; set; }
            public TrimAttribute(Type type)
            {
                Type = type;
            }
        }
        /// <summary>
        /// TrimAttribute:实现扩展方法Trim()  --必须是静态类、静态方法、第一个参数用this修饰
        /// </summary>
        public static class TrimAttributeExt
        {
            public static void Trim(this object obj)
            {
                Type tobj = obj.GetType();
                foreach (var prop in tobj.GetProperties())
                {
                    //GetCustomAttributes(typeof(TrimAttribute), false),返回TrimAttribute标识的特性
                    foreach (var attr in prop.GetCustomAttributes(typeof(TrimAttribute), false))
                    {
                        TrimAttribute tab = (TrimAttribute)attr;
                        if (prop.GetValue(obj) != null && tab.Type == typeof(string))
                        {
                            prop.SetValue(obj, GetPropValue(obj, prop.Name).ToString().Trim(), null);
                        }
                    }
                }
            }
            private static object GetPropValue(object obj, string propName)
            {
                //使用指定绑定约束并匹配指定的参数列表,调用指定成员
                return obj.GetType().InvokeMember(propName, BindingFlags.GetProperty, null, obj, new object[] { });
            }
        }
    特性类代码
        public class User
        {
            public int Id { get; set; }
            [Trim(typeof(string))]
            public string UserName { get; set; }
            [Trim(typeof(string))]
            public string Password { get; set; }
        }
    
     using static System.Console;//静态类可以使用using static
    namespace ConsoleTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                //DllImportDemo.Main();
    
                User user = new User { Id = 1, UserName = " admin     ", Password = " 1234 " };
                user.Trim();//该行行注释掉有空格
                WriteLine("|" + user.UserName + "|");
    
                ReadKey();
            }
        }
    }
    使用代码
  • 相关阅读:
    [BZOJ1584] [Usaco2009 Mar]Cleaning Up 打扫卫生(DP)
    [BZOJ1583] [Usaco2009 Mar]Moon Mooing 哞哞叫(队列)
    [BZOJ1582] [Usaco2009 Hol]Holiday Painting 节日画画(线段树)
    [BZOJ1579] [Usaco2009 Feb]Revamping Trails 道路升级(分层图最短路 + 堆优化dijk)
    [ZPG TEST 115] 字符串【归类思想】
    [ZPG TEST 114] 阿狸的英文名【水题】
    [USACO 2012 Open Gold] Bookshelf【优化dp】
    [USACO 2012 Mar Silver] Landscaping【Edit Distance】
    [USACO 2012 Mar Gold] Large Banner
    [USACO 2012 Feb Gold] Cow Coupons【贪心 堆】
  • 原文地址:https://www.cnblogs.com/Med1tator/p/6901602.html
Copyright © 2011-2022 走看看