C# 特性

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值