Diese generische Hilfsfunktion iteriert über eine Liste von Objekten, greift auf ihre öffentlichen Eigenschaften zu und spuckt eine durch Kommas getrennte Zeichenfolge pro Objekt aus.PropertyInfo.GetValue (obj, null) Abschneiden von Zeichenfolgen
/// <summary>
/// Format the properties as a list of comma delimited values, one object row per.
/// </summary>
/// <typeparam name="T">Type of class contained in the List</typeparam>
/// <param name="list">A list of objects</param>
/// <returns>a list of strings in csv format</returns>
public static List<string> ToCSV<T>(this IEnumerable<T> list)
where T : class
{
var results = new List<string>();
bool firstTime = true;
foreach (var obj in list)
{
// header data
if (firstTime)
{
firstTime = false;
string line = String.Empty;
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
line += propertyInfo.Name + ',';
}
}
results.Add(line);
}
else
{
string line = String.Empty;
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
object value = propertyInfo.GetValue(obj, null);
if (value.GetType() == typeof(string))
{
line += "\"" + value.ToString() + "\"" + ",";
}
else
{
line += value.ToString() + ",";
}
}
}
results.Add(line);
}
}
return results;
}
Eine der Klassen durch dieses Verfahren wiederholt wird, hat eine String-Eigenschaft, die abgeschnitten wird:
string BusinessItem { get; set; } // "0000", a legitimate business value
Die problematische Bit ist hier:
object value = propertyInfo.GetValue(obj, null); // value == 0
Wie komme ich der Wert der Eigenschaft als String, kein Int?
Wenn die Eigenschaft als Zeichenfolge definiert ist, wäre das Ergebnis eine Zeichenfolge. Etwas anderes scheint ein bisschen aus. –
Ja, ich kaufe das überhaupt nicht. Die Zahl "0000" ist gleichbedeutend mit der Zahl "0", so dass es wenig sinnvoll ist, eine beliebige Anzahl von "0" zu erwarten. Wenn es jedoch eine Zeichenkette ist, ist "0" viel anders als "0000". Ich denke, dass etwas anderes passiert. –
Bitte geben Sie ein kurzes, aber * vollständiges * Programm an, das das Problem demonstriert. –