Another function of reflection

Source: Internet
Author: User
Tags datetime reflection string format tostring

When it comes to reflection, I guess you are not unfamiliar, although many people do not know what is, of course, people think of it as "decompile", a bit like it, but can not be said to be decompile, although there is a "reverse" word, but there is no "compiled."

So I gave a reflection of such an overview, accurate or not, nor clear:

Reflection can dynamically get assembly information, or type information in an assembly, to facilitate dynamic invocation.

The benefit of dynamic invocation is that it saves resources, and usually we add an assembly reference to the project's reference, which means that as soon as the application runs, the assemblies will be loaded, whether you need to call them or not. For calls to fewer assemblies, if you consider loading at call time, the call is released, which will save memory footprint to some extent, this is not the only way to optimize the code, in fact, code optimization is not fixed rules, comprehensive and flexible to use a variety of techniques can optimize the code and improve performance.

Reflection focus on the "dynamic" on the word, I suddenly thought of data binding, so I think of something, usually we do the UI and the binding of the data, most of the time is known as the data item types have public properties, and then bound to a public property of the object. So imagine if we didn't know what the structure of the object from the data source was, or what public properties it had, so would it be troublesome to bind the data together?

This is obviously a problem, and the conventional way of thinking is difficult to solve, then we are not thinking of reflection? Whatever type of object comes from the data source, I just find all of its public properties by reflection, and then take the value of the corresponding property and then dynamically generate the UI interface. If so, is it cool?

I this person has a disadvantage, is once think of what tricks, will eagerly try, so apart, immediately throw away the things on hand, turn on the computer, start VS, try to coding up, this code is really not wasted effort, finally code out of my expected effect.

Here is my general idea:

First, you write a class that provides an action that converts a list of any type of object into a UI element in WPF, and then assigns the converted UI element list as a data source to the ItemsSource property of the listbox to complete the binding.

The advantage of doing this is that the class in the list of objects from the data source has several public properties, as long as it can be reflected.

The following is the code for the conversion class.

Using System;  
Using System.Collections;  
Using System.Collections.Generic;  
Using System.Linq;  
Using System.Text;  
Using System.Threading.Tasks;  
Using System.Reflection;  
Using System.Windows;  
Using System.Windows.Controls;  
Using System.Windows.Media;  
      
Using System.ComponentModel.DataAnnotations; Namespace MYAPP {public class Objectsconverttouifrmws {public ilist<frameworkelement> Buil  
            Duilist (IList objs) {list<frameworkelement> uilist = new list<frameworkelement> ();  
                foreach (Var obj in objs) {FrameworkElement Fe = Builduicore (obj);  
            Uilist.add (FE);  
        return uilist; Private propertyinfo[] Getpropertiesfromobj (object o) {return o.gettype (). GetProperties (BindingFlags.Public | 

 
        BindingFlags.Instance); } Private PanelBuilduicore (Object obj) {if (obj = = null) return null;  
      
            propertyinfo[] PiS = getpropertiesfromobj (obj);  
            Grid gridroot = new Grid ();  
            How many attributes are added to the number of rows, each line showing a gridRoot.ColumnDefinitions.Add (new ColumnDefinition {Width = Gridlength.auto});  
            GRIDROOT.COLUMNDEFINITIONS.ADD (new ColumnDefinition {Width = new GridLength (1, Gridunittype.star)}); for (int i = 0; i < PiS. Length;  
            i++) {gridRoot.RowDefinitions.Add (new RowDefinition () {Height = Gridlength.auto}); for (int n = 0; n < PiS. length;n++) {var attrs = Pis[n]. GetCustomAttributes (typeof (DisplayAttribute)).  
                ToArray (); Gets the value of the Property object VL = Pis[n].  
                GetValue (obj); If (VL is color) {//If the field represents a color, set to the background color color of the container BgcoLor = (Color) VL;  
                Gridroot.background = new SolidColorBrush (bgcolor);  
                    else {TextBlock tbdisplayname = new TextBlock (); if (attrs!= null && attrs. Count () > 0) {displayattribute dispattr = attrs[0] as DisplayAttribute  
                        ; Tbdisplayname.text = dispattr.  
                    Name;  
                    else {Tbdisplayname.text = "unknown field";  
                    } gridRoot.Children.Add (Tbdisplayname);  
                    Grid.setrow (Tbdisplayname, N);  
                    Grid.setcolumn (tbdisplayname, 0);  
                    TextBlock tbvalue = new TextBlock (); If the property type is DateTime, the conversion string format if (VL is DateTime) {Tbvalu E.text = ((datetIME) VL).  
                    ToString ("Yyyy-mm-dd HH:mm:ss");  
                        else if (VL is double) {//If it is a double-precision type, keep three decimal digits Tbvalue.text = ((double) VL).  
                    ToString ("N3"); else {Tbvalue.text = vl.  
                    ToString ();  
                    } gridRoot.Children.Add (Tbvalue);  
                    Grid.setrow (Tbvalue, N);  
                Grid.setcolumn (Tbvalue, 1);  
        } return gridroot; }  
    }  
}

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.