c# - How to remove repetitive code that differ in using properties/fields for displaying themselves as strings? -


I have two extension methods that are very similar. I want to remove code duplicate from pattern or similar, but it can not actually get it to work.

The code looks like this:

  Public Stabilized String GetPublicPropertiesAsString (this object @this) {return @ this.GetType (). GetProperties (). Select (propertyInfo => {var propertyValue = propertyInfo.GetValue (obj: @this, invokeAttr: BindingFlags.Public, binder: null, ("00:00:00"): "[blank]"; "{0 }: "Remove" to return to "{1}". Format (PropertyFireFileName, PropertyAvailabilityStestString);}) JoinAsString (Environmental New Line);} Public Stabilized String GetFieldsAsString (this object @this) {return @ this Select GetFields (). Select (fieldInfo => {var fieldValue = fieldInfo.GetValue (@this); var fieldValueAsString = fieldValue! = Null? FieldValue.ToString (). Remove Remove ("00:00 : 00 "):" [empty] "; Return to" {0}: {1} ". FormatWith (fieldInfo. Name, fieldValueAsString);}) JoinAsString (Environment new line);}  

Can repeating code be repeated again?

Note

JoinAsString , RemoveAll , and with format . = "Post-text" itemprop = "text">

Yes, this can be generic and the fact that both Exit from PropertyInfo and FieldInfo MemberInfo are used by

something like this:

Fixed String GetAsString & lt; T & gt; (Object @ this, funx & lt; T, object & gt; recipient) where T: member info {return @ this.GetType (). GetMembers (/ * binding flags * /). OfType & lt; T & gt; (). Select (x = & gt; {value value = getter (x); var valueAsString = value! = Null? Value.ToString (.) Remove Remove ("00:00:00"): "[null]"; Return "{0}: {1}" FormatWith (x.Name, valueAsString);}). JoinAsString (); }

Now hook up:

  GetPublicPropertiesAsString public static string (this object @this) {GetAsString & lt; PropertyInfo & gt; (@ This, x => X. gate value (@ this, tap)); } Public Stabilized String GetPublicFieldsAsString (this object @this) {return GetAsString & lt; FieldInfo & gt; (@ This, x => x.getValue (@this)); }  

Comments