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();
            }
        }
    }
    使用代码
  • 相关阅读:
    RE
    【LeetCode】198. House Robber
    【LeetCode】053. Maximum Subarray
    【LeetCode】152. Maximum Product Subarray
    【LeetCode】238.Product of Array Except Self
    【LeetCode】042 Trapping Rain Water
    【LeetCode】011 Container With Most Water
    【LeetCode】004. Median of Two Sorted Arrays
    【LeetCode】454 4Sum II
    【LeetCode】259 3Sum Smaller
  • 原文地址:https://www.cnblogs.com/Med1tator/p/6901602.html
Copyright © 2011-2022 走看看