C # Reflection iterates through all the fields of an entity, with a detailed description of the ObjectDumper class implementation

Source: Internet
Author: User
Tags string back
When logging, it is sometimes necessary to know the value of each field of an entity, when it is necessary to iterate through the members with reflection, to spell the string back, and if the member is still a custom type, recursive execution is required.

Implementation method:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Reflection;using System.collections;namespace servertoolserver.util{public class ObjectDumper {//<summary>//        /The maximum number of bytes for this record///</summary> private static int MAXLENGTH = 16384;        <summary>////The object currently being logged///</summary> private static object lastobj = NULL; <summary>///reflect the field name and field values of obj////</summary>//<typeparam name= "T" > type to reflect </        typeparam>//<param name= "obj" > Entities </param>//<returns> field names: Field values </returns>            public static string Getobjstr (Object obj) {if (obj = = null) {return "";            } StringBuilder ret = new StringBuilder (30); fieldinfo[] fields = obj. GetType ().            GetFields (); if (fields = = NULL | | fields.           Length = = 0) {return ret.            ToString ();                    } else {foreach (FieldInfo eachfield in fields) {                Getobjstr (obj, Eachfield, ret); }} return ret.        ToString (); }///<summary>//reflect the field name of the object: Value///</summary>//<param Name= "entity" > Objects </param>//<param name= "obj" > Fields </param>///<param name= "str" > recorded STRINGBUILDER&L            t;/param> public static void Getobjstr (object entity, Object obj, StringBuilder str) {try                {////avoids infinite recursion, ensuring that an object is only recorded once if (Object.referenceequals (obj, lastobj))                {return;                } lastobj = obj;                if (entity = = NULL | | obj = = NULL) {return; } if (str. Length > Maxlength) {str.                    Append ("... to long ...");                Return                } FieldInfo f = obj as FieldInfo; String TypeName = f = = null? Obj. GetType ().                Name:f.name; Type type = F = = null? Obj.                GetType (): F.fieldtype; Object value = f = = null?                Obj:f.getvalue (entity); if (type. Isvaluetype | | Type = = typeof (String)) {if (str. Length > MAXLENGTH) {str.                        Append ("... to long ...");                    Return } str.                    Append (TypeName); Str.                    Append (":"); Str.                    Append (value); Str.                    Append ("\ r \ n");                Return ////if the member is a collection, recursively traverse if (typeof (IEnumerable).   IsAssignableFrom (type)) {IEnumerable ie = value as IEnumerable;                 if (ie = null) {IEnumerator list = ie.                        GetEnumerator (); while (list. MoveNext ()) {////basic data type or string if (list. Current.gettype (). Isvaluetype | | List. Current.gettype () = = typeof (String)) {if (str. Length > MAXLENGTH) {str.                                    Append ("... to long ...");                                Return } else {str.                                    Append (type); Str.                                    Append (":"); Str. Append (list.                                    Current); Str.                                Append ("\ r \ n"); }}////Custom type                           else {str. Append (list.                                Current.gettype ()); Str.                                Append ("."); fieldinfo[] fields = list. Current.gettype ().                                GetFields (); foreach (FieldInfo subField in fields) {if (str. Length > MAXLENGTH) {str.                                        Append ("... to long ...");                                    Return } getobjstr (list.                                Current, SubField, str);                }}}}} else {str.                    Append (type); Str.                    Append ("."); fieldinfo[] fields = type.           GetFields ();         if (fields.                    Length = = 0) {return; } foreach (FieldInfo subField in fields) {if (str. Length > MAXLENGTH) {str.                            Append ("... to long ...");                        Return                    } getobjstr (value, SubField, str);            }}} catch (Exception ex) {return; }        }    }}

The above is the C # reflection traversal of all fields of the entity, ObjectDumper class implementation of the details of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.