c#面向对象(六)

预处理指令

小理解

  定义:预处理指定主要用于指导编译器进行编译前的信息处理。怎么才是预处理指定呢?也就是#region:含义呢,就是折叠代码的预处理指定,称之为区域预处理指定,语法:#指令名。

练习

#define COND//定义条件的预处理指令
#undef COND//取消条件的预处理指令
#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 预处理指令
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //条件判断预处理指令
#if COND
            Console.WriteLine("cond");
#elif DEBUG
Console.WriteLine("debug");
#else
Console.WriteLine("nocond");
#endif
            //行预处理指令(可以指定错误信息和警告信息的行号和文件)
#line 200 "Text.cs"
            //错误和警告信息预处理指令
#error 错误信息
#warning 警告信息

反射

反射-Type


            #region//type
            //定义:反射就是使用代码动态的获取类型信息
            //分析:
            //类型:值类型,引用类型,
            //信息:成员字段,属性
            //如果需要获取类型信息,那么必须先获取type类对象
            //Type类
            //该类是一个抽象类,可以通过三种形式获取指定类型的Type类对象
            //对象.GetType()
            //typeof(命名空间.类名)
            //Type.GetType("命名空间.类名")
            //获取值类型得Type类对象
            Type type01=12.GetType();
            Type type02 = typeof(System.Int32);
            Type type03 = Type.GetType("System.Int32");
            //判断三个type类对象是否相同
            Console.WriteLine(type01 == type02);
            Console.WriteLine(type03 == type02);
            //一个类型的type,类对象通过不同的方式获取的对象是同一个

            //获取引用类型的Type类对象:object
            Type type04 = new object().GetType();
            Type type05=typeof(System.Object);
            Type type06=Type.GetType("System.Object");
            Console.WriteLine(type04 == type05);
            Console.WriteLine(type05 == type06);
            //Console.ReadKey();
            #endregion

反射-Field

 class Person
        {
            //私有字段
            private int id=111;
            public string name = "lucky";
            //静态字段
            public static string nation;
        }
  #region //Field
            //获取Person类型数据
            Type type= typeof(Program.Person);
            //获取字段,获取所有public的字段
            //FieldInfo[] fieldInfos=type.GetFields();//GetFields返回当前type所有的公共字段
            //fieldinfo发现字段的属性并提供对字段元数据的访问权限
            //获取共有的静态字段
            //FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Static|BindingFlags.Public);
            //获取非公有的实例字段
            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance|BindingFlags.NonPublic);
            //遍历
            for (int i=0; i<fieldInfos.Length; i++)
            {
                Console.WriteLine($"字段类型={fieldInfos[i].FieldType},字段名称={fieldInfos[i].Name},字段值={fieldInfos[i].GetValue(new Person())}");
            }
            //获取指定字段
            FieldInfo field = type.GetField("nation");//搜索指定名称的共有字段
            //设置值,静态字段不需要对象,因此传递null
            field.SetValue(null, "成都");
            //获取值
            Console.WriteLine(field.GetValue(null));
            Console.ReadKey();
            #endregion

反射-Property

      public int Id { get => id; set => id = value; }
            public string Name { get => name; set => name = value; }
            public static string Nation { get => nation; set => nation = value; }
#region  //Property
            Type type=new Person().GetType();
            //获取所有共有的属性
            //和Field类似
            PropertyInfo[] propertyInfos = type.GetProperties();
            //遍历
            foreach (PropertyInfo property in propertyInfos)
            {
                Console.WriteLine($"属性类型={property.PropertyType},属性名={property.Name},属性值={property.GetValue(new Person())}");
            }
            //获取指定属性
            PropertyInfo info = type.GetProperty("Nation");
            //设置值
            info.SetValue(null,"吐鲁番");
            Console.WriteLine(info.GetValue(null));
            Console.ReadKey();

反射-Constructor

 class Person
    {
        //字段
        private int id = 100;
        private string name = "jacr";
        private int age = 20;
        private static string nation;
        //构造函数
        private Person() { }
        public Person(int id, string name, int age)
        {
            this.id = id;
            this.name = name;
            this.age = age;
        }
        static Person()
        {
            nation = "吐鲁番";
        }
        //重写ToString()
        public override string ToString()
        {
            return $"person[id={this.id},name={this.name},age={this.Age}]";
        }
        //属性
        public int Id { get => id; set => id = value; }
        public string Name { get => name; set => name = value; }
        public int Age { get => age; set => age = value; }
        public static string Nation { get => nation; set => nation = value; }
        //构造函数
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(Person);
            //获取公有的构造函数
            ConstructorInfo[] constructorInfos = type.GetConstructors();
            //获取静态非公有的构造函数
            // ConstructorInfo[] constructorInfos = type.GetConstructors(BindingFlags.Static|BindingFlags.NonPublic);
            //获取非静态非公有构造函数
            //ConstructorInfo[] constructorInfos = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (ConstructorInfo item in constructorInfos)
            {
                Console.WriteLine($"构造函数名;{item.Name},构造函数参数个数={item.GetParameters().Length},是否静态={item.IsStatic}");
            }
            //获取指定的构造函数
            ConstructorInfo constructorInfo = type.GetConstructor(new Type[] { typeof(int), typeof(string), typeof(int) });
            //创建对象
            Person person=constructorInfo.Invoke(new object[] {200,"luck",90}) as Person;
            Console.WriteLine(person);
            //获取静态构造函数
            ConstructorInfo cons = type.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic)[0];
            //cons.Invoke(null);
            //获取
            Console.WriteLine(Person.Nation);
            Console.ReadKey();

反射-Method

 //字段
        private int id = 100;
        private string name = "jacr";
        private int age = 20;
        private static string nation;
        //构造函数
        private Person() { }
        public Person(int id, string name, int age)
        {
            this.id = id;
            this.name = name;
            this.age = age;
        }
        static Person()
        {
            nation = "吐鲁番";
        }
        //重写ToString()
        public override string ToString()
        {
            return $"person[id={this.id},name={this.name},age={this.Age}]";
        }
        //介绍函数
        public string Introduce()
        {
            return $"我是{this.name}编号={this.id},今年{this.age},住在{nation}";
        }
        //静态构造函数
        public static void ShowNation(string nation)
        {
            Nation = nation;
            Console.WriteLine($"国籍={Nation}");
        }
   Type type= typeof(Person);
            //获取共有函数
            //MethodInfo[] methodInfos = type.GetMethods();
            MethodInfo[] methodInfos = type.GetMethods(BindingFlags.Instance|BindingFlags.DeclaredOnly|BindingFlags.Public);

            //遍历
            foreach (MethodInfo member in methodInfos)
            {
                Console.WriteLine($"函数返回值类型{member.ReturnType},函数名:{member.Name},函数参数长度={member.GetParameters().Length}");
            }
            //获取指定的函数、
            MethodInfo method = type.GetMethod("Introduce", new Type[] { });
            Console.WriteLine(method.Invoke(new Person(1003,"peter",24),null));
            //获取静态函数
            MethodInfo info = type.GetMethod("ShowNation", new Type[] { typeof(string) });
            info.Invoke(null,new object[] { "中国"});
            Console.ReadKey();


系统特性

 class Text
    {
        //错误方法
        [Obsolete("错误哦",false)]
        public void OldMethod() {
            Console.WriteLine("Text.OldMethod");
        }
        //新方法
        public void NewMethod() {
            Console.WriteLine("Text.NewMethod"); 
        }
        //[Serializable]
        //    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
        //    [ComVisible(true)]
        //    public sealed class SerializableAttribute : Attribute
        //    {
        //        internal static Attribute GetCustomAttribute(RuntimeType type)
        //        {
        //            if ((type.Attributes & TypeAttributes.Serializable) != TypeAttributes.Serializable)
        //            {
        //                return null;
        //            }

        //            return new SerializableAttribute();
        //        }

        //        internal static bool IsDefined(RuntimeType type)
        //        {
        //            return type.IsSerializable;
        //        }
        //    }
        //}
        //[Serializable]
        //AttributeUsage特性指定该定义的特性可以标记哪些事物
        //[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
        //[ComVisible(true)]
        //[__DynamicallyInvokable]
        //定义了一个继承自Attribute的类,该类是一个密封类,不能再被继承
        //public sealed class ObsoleteAttribute : Attribute
        //{
        //属性
        //    private string _message;

        //    private bool _error;

        //    [__DynamicallyInvokable]
        //    public string Message
        //    {
        //        [__DynamicallyInvokable]
        //        get
        //        {
        //            return _message;
        //        }
        //    }

        //    [__DynamicallyInvokable]
        //    public bool IsError
        //    {
        //        [__DynamicallyInvokable]
        //        get
        //        {
        //            return _error;
        //        }
        //    }

        //    [__DynamicallyInvokable]
        //构造函数
        //    public ObsoleteAttribute()
        //    {
        //        _message = null;
        //        _error = false;
        //    }

        //    [__DynamicallyInvokable]
        //    public ObsoleteAttribute(string message)
        //    {
        //        _message = message;
        //        _error = false;
        //    }

        //    [__DynamicallyInvokable]
        //    public ObsoleteAttribute(string message, bool error)
        //    {
        //        _message = message;
        //        _error = error;
        //    }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            //基本定义;特性指的是一种允许程序员向程序添加元数组的语言结构,用于存储程序结构信息的特殊类
            //语法:[特性名(参数列表)]就是调用特性类的构造函数
            //常用特性:Obsolete:该特性用于标注类或成员已经被弃用,提示错误信息或警告信息
            //Serializable:该特性用于标注类是可以序列化
           new Text().OldMethod();
            new Text().NewMethod();

自定义特性


    //自定义特性,继承自Attribute
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Field| AttributeTargets.Property|AttributeTargets.Method,AllowMultiple = true)]
    class RecordAttribute : Attribute
    {
        private string type;//定义操作类型
        private string author;//定义作者
        private string dateTime;//定义日期
        private string desc;//定义描述
        public RecordAttribute() { }
        public RecordAttribute(string type, string author, string dateTime, string desc)
        {
            this.type = type;
            this.author = author;
            this.dateTime = dateTime;
            this.desc = desc;
        }

        public string Type { get => type; set => type = value; }
        public string Author { get => author; set => author = value; }
        public string DateTime { get => dateTime; set => dateTime = value; }
        public string Desc { get => desc; set => desc = value; }
    }
    //自定义一个特性测试类
    [Record("新增","lucky","2-2-2","该类用于测试自定义特性")]
    [Record("更新","peter","1-1-1","用于将类修改为Test.cs")]
    class Text
    {
        private string name;

        public string Name { get => name; set => name = value; }
        [Record("修改","one","0-0-0","用于修改输出函数")]
        public void Print()
        {
            Console.WriteLine("Print()");
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            //使用反射机制获取成员的特性
            Type type=typeof(Text);
            //判断类上是否有指定的特性标注
            if (type.IsDefined(typeof(RecordAttribute),false))
            {
                object[] objs=type.GetCustomAttributes(typeof(RecordAttribute), false);
                foreach (RecordAttribute attribute in objs)
                {
                    Console.WriteLine(attribute);
                    Console.WriteLine("" + attribute.Type);
                    Console.WriteLine("" + attribute.Author);
                    Console.WriteLine(""+attribute.DateTime);
                    Console.WriteLine(""+attribute.Desc);
                }
            }
            //获取函数上的标记
            MethodInfo methodInfo=type.GetMethod("Print",new Type[] {});
            if (methodInfo.IsDefined(typeof(RecordAttribute), false))
            {
                Object[] objs=methodInfo.GetCustomAttributes(typeof(RecordAttribute), false);
                foreach (RecordAttribute attribute in objs)
                {
                    Console.WriteLine(attribute);
                    Console.WriteLine("" + attribute.Type);
                    Console.WriteLine("" + attribute.Author);
                    Console.WriteLine("" + attribute.DateTime);
                    Console.WriteLine("" + attribute.Desc);
                }
            }
            Console.ReadKey();

猜你喜欢

转载自blog.csdn.net/weixin_51983027/article/details/129909399