Logging Zustand des Objekts. Immer alle seine Eigenschaftswerte als string
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
......
var emp1Address = new Address();
emp1Address.AddressLine1 = "Microsoft Corporation";
emp1Address.AddressLine2 = "One Microsoft Way";
emp1Address.City = "Redmond";
emp1Address.State = "WA";
emp1Address.Zip = "98052-6399";
Beachten Sie die obige Klasse und später in der Initialisierung. Irgendwann möchte ich zu Protokoll, seinen Zustand, wenn der Fehler Auftritt. Ich würde gerne die string-log etwas wie unten.
string toLog = Helper.GetLogFor(emp1Address);
sting toLog sollte so Aussehen wie unten.
AddressLine1 = "Microsoft Corporation";
AddressLine2 = "One Microsoft Way";
City = "Redmond";
State = "WA";
Zip = "98052-6399";
Dann will ich log toLog
string.
Wie kann ich den Zugriff auf alle Eigenschaftsnamen und Eigenschaftswerte eines Objekts innerhalb Helper.GetLogFor()
Methode?
Lösung, die ich umgesetzt habe:-
///<summary>
///Creates a string of all property value pair in the provided object instance
///</summary>
///<param name="objectToGetStateOf"></param>
///<exception cref="ArgumentException"></exception>
///<returns></returns>
public static string GetLogFor(object objectToGetStateOf)
{
if (objectToGetStateOf == null)
{
const string PARAMETER_NAME = "objectToGetStateOf";
throw new ArgumentException(string.Format("Parameter {0} cannot be null", PARAMETER_NAME), PARAMETER_NAME);
}
var builder = new StringBuilder();
foreach (var property in objectToGetStateOf.GetType().GetProperties())
{
object value = property.GetValue(objectToGetStateOf, null);
builder.Append(property.Name)
.Append(" = ")
.Append((value ?? "null"))
.AppendLine();
}
return builder.ToString();
}
- War es einigen Grund, nicht mit der Serialisierung?
- Ich wollte es in für Menschen lesbaren format, so dass wenn immer ich hatte, um zu sehen, über die Protokolle, kann ich schnell sehen, was waren die Werte in die Eigenschaft des Objekts, das zum Zeitpunkt des Fehlers.
Du musst angemeldet sein, um einen Kommentar abzugeben.
Argument typ 'object' is not assignable to parameter type 'string'
der Kompilierung Fehler aufbuilder.Append(property.Name).Append(" = ").AppendLine(property.Value);
- Anweisung.GetProperties(BindingFlags.Public | BindingFlags.Instance)
bedeuten?AppendLine
nicht den gleichen Satz von überlastungen wieAppend
.ToString
nennen würde einNullReferenceException
für eine null-Eigenschaft-Wert.Können Sie auf die Eigenschaft name mit der spiegelung
wie folgende