mardi 23 janvier 2018

GetValue reflection on iterating through collections and get item.ToString()

Inside Class:

public HashSet<string> Test = new HashSet<string>();
public List<string> Test2 = new HashSet<string>();
public String Test3 = "lol";

Getting all properties with reflection:

var properties = class.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

Now I want to iterate through the collection properties only:

if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType) && property.PropertyType != typeof(string))
{
    var valueString = string.Empty;
    foreach (var item in (IEnumerable)value)
    {
        valueString += item.ToString() + " | ";
    }
}

Works fine. Except when the collection is empty I get the collection fullname on item.ToString() instead of nothing / string.empty. Any way to fix that?





Aucun commentaire:

Enregistrer un commentaire