Attribute + Reflection to improve code reuse

Source: Internet
Author: User

This article aims to broaden the design concept and use the instance code.

The design idea comes from the first version of article 24 in Objective c #: Declarative Programming rather than imperative programming is preferred. In particular, you want to provide default sorting for multiple attributes, not just based on one attribute, but also by calling the IComparable interface implemented by Object Attributes first, if no interface is implemented, call IComparable for comparison. The sorting class is generic to ensure type security.

General idea: Attribute is used to describe the class we want to obtain metadata. Reflection is used to extract metadata and some object-independent component functions are implemented based on the extracted metadata.

In this example, we will use Attribute to decorate the Class Object and set the default sorting Attribute of the object. sort by the default sorting Attribute.

 [DefaultSort( [] {,          ID { ;         Name { ;         Value { ;                    String.Format(  }

For SortData objects, we want to sort them by their IDs. If the IDs are equal, they are sorted by the Name attribute. Like its name implies, This is the default behavior. We do not need to implement the IComparable <SortData> interface of SortData. We will change the sorting rules in the future, you only need to modify the content of the attribute name array in DefaultSort, which is convenient.

The DefaultAttribute recorded in the original book can only be sorted by one attribute name, which is not practical enough. It is expected to record the names of multiple attributes like the following class.

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple=                                           {               { m_propNames =            DefaultSortAttribute(              m_propNames =              DefaultSortAttribute(              m_propNames =      }

Note that the constructor that only wants to sort by one attribute is retained. When decorating the class, put [DefaultSort (new string [] {"ID ", "Name"})] and [DefaultSort ("ID")] similar declarations are enough.

Since the class is decorated with Attribute, You Need To Know such metadata. The following uses Reflection to read the default Attribute name to be sorted. The improvement compared with the original book is, use the generic and the IComparable <T> API that gives priority to attributes to compare and sort data.

                DefaultSortComparer<T> : IComparer, IComparer<T>                       m_reverse =             m_valueType =                        (            DefaultSortComparer(              m_reverse =             Type t =              m_valueType =              [] a = t.GetCustomAttributes((DefaultSortAttribute),                             (a.Length !=                                 DefaultSortAttribute sortName = a[]               [] propNames =              m_sortProps =               PropertyDescriptorCollection props =               ( i = ; i < propNames.Length; i++                  (PropertyDescriptor p                       (p.Name ==                     m_sortProps[i] =                                    IComparer.Compare( left,                (HasNull(left, right) ==                    nullCompare =                   m_reverse ? -                (left.GetType() !=                   ArgumentException(               ((T).IsAssignableFrom(left.GetType()) ==                    ArgumentException(                                         (m_valueType ==  && HasNull(x, y) ==                   nullCompare =                  m_reverse ? -                ( prop                   xValue =                  yValue =                   (HasNull(xValue, yValue) ==                       nullCompare =                       m_reverse ? -                   Type propType =                                    ((IComparable<>                      MethodInfo methodInfo = propType.GetMethods().FirstOrDefault(method => method.Name ==                          && method.GetParameters().Length ==                          && method.GetParameters()[].ParameterType ==                       gretValue = ()methodInfo.Invoke(xValue,                         (gretValue == )                        m_reverse ? -                   IComparable xNonGeneric = xValue                  IComparable yNonGeneric = yValue                    (xNonGeneric ==                        ArgumentException( + prop.Name +                    retValue =                   (retValue == )                    m_reverse ? -                            CompareWithNull( left,                ((left == ) && (right ==                                  (left ==                   -                           HasNull( left,                (left ==  || right ==                                    }

 

It should be noted that DefaultSortComparer <T> is generic and implements the IComparer and IComparer <T> interfaces to facilitate sorting.


How can I use the code with so many posts.

  data1 =  SortData() { ID = , Name = , Value =   data2 =  SortData() { ID = , Name = , Value =   data3 =  SortData() { ID = , Name = , Value =   data4 =  SortData() { ID = , Name = , Value =   List<SortData> sortData =  List<SortData>      sortData.Sort( DefaultSortComparer<SortData>(  sortData.ForEach(data => Console.WriteLine(data));


The results won't be ugly. After testing, they can work normally.

Through this example, we can see that the key to implementing it is that Attribute is responsible for the decoration class, and Reflection is responsible for reading the metadata information after the decoration of the specific Attribute to implement components unrelated to the specific class type. One Coding, multiple reuse.

I hope you will have more support and some interesting out-of-the-box code will be available in the future.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.