J'ai deux méthodes d'extension qui sont très similaires. Je voudrais supprimer le code duplique avec «the hole in the middle» modèle ou similaire, mais ne peut pas vraiment le faire fonctionner.Comment supprimer le code répétitif qui diffère en utilisant les propriétés/champs pour s'afficher eux-mêmes en tant que chaînes?
Le code ressemble à ceci:
public static String GetPublicPropertiesAsString(this Object @this)
{
return @this.GetType().GetProperties()
.Select(propertyInfo =>
{
var propertyValue = propertyInfo.GetValue(obj: @this,
invokeAttr: BindingFlags.Public,
binder: null,
index: null,
culture: null);
var propertyValueAsString = propertyValue != null ? propertyValue.ToString().RemoveAll("00:00:00") : "[null]";
return "{0}: {1}".FormatWith(propertyInfo.Name, propertyValueAsString);
}).JoinAsString(Environment.NewLine);
}
public static String GetFieldsAsString(this Object @this)
{
return @this.GetType().GetFields()
.Select(fieldInfo =>
{
var fieldValue = fieldInfo.GetValue(@this);
var fieldValueAsString = fieldValue != null ? fieldValue.ToString().RemoveAll("00:00:00") : "[null]";
return "{0}: {1}".FormatWith(fieldInfo.Name, fieldValueAsString);
}).JoinAsString(Environment.NewLine);
}
le code répétitif ci-dessus pourrait être remaniée loin? Remarque: JoinAsString
, RemoveAll
et FormatWith
sont mes propres méthodes d'extension.
+1 et accepté. Merci! –