博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 特性
阅读量:2026 次
发布时间:2019-04-28

本文共 4911 字,大约阅读时间需要 16 分钟。

using System;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;using System.Runtime.InteropServices;using System.Reflection;namespace ConsoleApplication12{    #region 序列化特性    /*    [Obsolete]    class Program    {        static void Main(string[] args)        {            /*  把对象序列化存储在文件中            Person me = new Person();            me.Age = 34;            me.WeightInPounds = 200;            Stream s = File.Open(@"C:\Users\Administrator\Desktop\test.txt", FileMode.Create);            BinaryFormatter bf = new BinaryFormatter();            bf.Serialize(s, me);            s.Close();            Console.ReadLine();            */    /*  把对象从文件中反序列化读取    Stream s = File.Open(@"C:\Users\Administrator\Desktop\test.txt", FileMode.Open);    BinaryFormatter bf = new BinaryFormatter();    object o = bf.Deserialize(s);    Person p = o as Person;    if (p != null)        Console.WriteLine("DeSerialized Person aged:{0} whight:{1}", p.Age, p.WeightInPounds);    s.Close();    */    /*  把对象序列化存储在文件中    MyObject obj = new MyObject();    obj.n1 = 1;    obj.n2 = 24;    obj.str = "一些字符串";    IFormatter formatter = new BinaryFormatter();    Stream stream = new FileStream(@"C:\Users\Administrator\Desktop\test.txt", FileMode.Create,    FileAccess.Write, FileShare.None);    formatter.Serialize(stream, obj);    stream.Close();    /* 把对象从文件中反序列化读取    IFormatter formatter = new BinaryFormatter();    Stream stream = new FileStream(@"C:\Users\Administrator\Desktop\test.txt", FileMode.Open,    FileAccess.Read, FileShare.Read);    MyObject obj = (MyObject)formatter.Deserialize(stream);    stream.Close();    // 下面是证明    Console.WriteLine("n1: {0}", obj.n1);    Console.WriteLine("n2: {0}", obj.n2);    Console.WriteLine("str: {0}", obj.str);}}[Serializable]public class Person{public Person(){}public int Age;public int WeightInPounds;}[Serializable]public class MyObject{public int n1 = 0;public int n2 = 0;public string str = null;}*/    #endregion    #region [In][Out]特性    /*class TT{    public static void F([In] ref int a)    {        a += 1;    }    static void Main(string[] args)    {        int a = 0;        TT.F(ref a);        Console.WriteLine(a);    }}*/    #endregion    #region 自定义特性 验证字符串输入长度    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]    public sealed class MyStringLenthAttribute : Attribute    {        public MyStringLenthAttribute(string displayName, int maxLength)        {            this.MaxLength = maxLength;            this.DisplayName = displayName;        }        //显示的名称,对外是只读的,所以不能通过可选参数来赋值,必须在构造函数中对其初始化。        public string DisplayName { get; private set; }        //长度最大值,对外是只读的,所以不能通过可选参数来赋值,必须在构造函数中对其初始化。        public int MaxLength { get; private set; }        //错误信息,标注时可作为可选命名参数来使用。        public string ErrorMessage { get; set; }        //长度最小值,标注时可作为可选命名参数来使用。        public int MinLength { get; set; }    }    // 应用自定义MyStringLenth特性于Order类的OrderID属性之上。MinLength和ErrorMessage是命名参数。    public class Order    {        [MyStringLenth("订单号", 6, MinLength = 3, ErrorMessage = "{0}的长度必须在{1}和{2}之间,请重新输入!")]        public string OrderID { get; set; }    }    class EXE    {        //检查成员字符串长度是否越限。        private static bool IsMemberValid(int inputLength, MemberInfo member)        {            foreach (object attribute in member.GetCustomAttributes(true))            {                if (attribute is MyStringLenthAttribute)                {                    MyStringLenthAttribute attr = (MyStringLenthAttribute)attribute;                    string displayName = attr.DisplayName;                    int maxLength = attr.MaxLength;                    int minLength = attr.MinLength;                    string msg = attr.ErrorMessage;                    if (inputLength < minLength || inputLength > maxLength)                    {                        Console.WriteLine(msg, displayName, minLength, maxLength);                        return false;                    }                    else {                        return true;                    }                }            }            return false;        }        //验证输入是否合法        private static bool IsValid(Order order)        {            if (order == null) return false;            foreach (PropertyInfo p in typeof(Order).GetProperties())            {                if (IsMemberValid(order.OrderID.Length, p))                    return true;            }            return false;        }        public static void Main()        {            string input = string.Empty;            Order order;            do            {                Console.WriteLine("请输入订单号:");                input = Console.ReadLine();                order = new Order { OrderID = input };            }            while (!IsValid(order));            Console.WriteLine("订单号输入正确,按任意键退出!");            Console.ReadKey();        }    }    #endregion}

转载地址:http://dtdaf.baihongyu.com/

你可能感兴趣的文章
对深拷贝与浅拷贝的再次理解
查看>>
函数popen()
查看>>
Linux线程同步 屏障
查看>>
TCP 的那些事儿(上)
查看>>
TCP 的那些事儿(下)
查看>>
TCP的拥塞控制
查看>>
每天进步一点点——Linux中的线程局部存储(二)
查看>>
【C++】explicit关键字
查看>>
八大排序算法
查看>>
C++ 11
查看>>
Spring @Configuration 和 @Component 区别
查看>>
JVM内存模型
查看>>
springbootTestDao
查看>>
一张表里面有ID自增主键,当insert了17条记录之后,删除了第15,16,17条记录,再把mysql重启,再insert一条记录,这条记录的ID是18还是15 ?
查看>>
RabbitMQ 相关问题总结--RabbitMQ 如何确保消息发送和消费?
查看>>
Spring循环依赖及解决方式
查看>>
深入理解CAS机制
查看>>
Spring的启动流程
查看>>
判断单链表是否有环,并找出环的入口【python】
查看>>
在mybatis中#{}和${}的区别,使用场景及sql注入
查看>>