mardi 6 octobre 2015

Howto search through Properties of all kinds of types

I have a base class called Part and derived classes like Wire or Connector and many more that inherit from Part.

Now I want to implement a search function that searches all Properties of the derived classes for a string.

If necessary that string should be tried to be converted to the type of the Property. The Properties can also be Lists and should be searched on the first level.

class Part 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Wire : Part
{
    public NumberWithUnit Diameter { get; set; }
    public Weight Weight { get; set; }
}

class Connector : Part
{
    public List<Part> ConnectedParts { get; set; }
}

I know how to generally search through the Properties of base types with Reflection like this

private bool SearchProperties<T>(T part, string searchString) where T : Part
{
    var props = typeof(T).GetProperties();
    foreach (var prop in props)
    {
        var value = prop.GetValue(part);
        if (value is string)
        {
            if (string.Equals(value, searchString))
                return true;
        }
        else if (value is int)
        {
            int v;
            if (int.TryParse(searchString, out v))
            {
                if(v == (int) value)
                    return true;
            }
        }
        return false;
    }
}

But that would be a long list of types and I have Properties of Type Weight for instance and many more. Is there some kind of general way to search without casting all types?





Aucun commentaire:

Enregistrer un commentaire