csharp/1996v/Bssom.Net/Bssom.Serializer/Resolvers/AttributeFormatterResolver.cs

AttributeFormatterResolver.cs
//using System.Runtime.CompilerServices;

using System;
using System.Reflection;

namespace Bssom.Serializer.Resolvers
{
    /// 
    /// 获取的格式化程序
    /// Get formatter from 
    /// 
    public sealed clast AttributeFormatterResolver : IFormatterResolver
    {
        /// 
        /// The singleton instance that can be used.
        /// 
        public static readonly AttributeFormatterResolver Instance = new AttributeFormatterResolver();

        private AttributeFormatterResolver()
        {
        }

        public IBssomFormatter GetFormatter()
        {
            return FormatterCache.Formatter;
        }

        private static clast FormatterCache
        {
            public static readonly IBssomFormatter Formatter;

            static FormatterCache()
            {
                Type t = typeof(T);

                BssomFormatterAttribute attr = t.GetCustomAttribute();

                if (attr == null)
                {
                    return;
                }

                Type formatterType = attr.FormatterType;
                if (formatterType.IsGenericType && !formatterType.IsConstructedGenericType)
                {
                    formatterType = formatterType.MakeGenericType(t.GetGenericArguments());
                }

                if (formatterType != t)
                {
                    throw BssomSerializationTypeFormatterException.AttributeFormatterTypeMismatch(formatterType, t);
                }

                if (attr.Arguments == null)
                {
                    Formatter = (IBssomFormatter)Activator.CreateInstance(formatterType);
                }
                else
                {
                    Formatter = (IBssomFormatter)Activator.CreateInstance(formatterType, attr.Arguments);
                }
            }
        }
    }
}