mardi 23 novembre 2021

Check specific values of generic properties

Well, I always can hardcode checking properties in order to solve my case but I want to do it using reflection.

My generic type:

public class AnalyzedParameter<T>
{
    public T Value { get; set; }

    public bool Valid { get; set; }
}

My class:

public class Foo
{
    public AnalyzedParameter<int> A { get; set; }

    public AnalyzedParameter<string> B { get; set; }
}

I need to check each property that has type AnalyzedParameter by checking Valid property inside.

So my method has to be like this:

public bool IsValid()
    {
        var props = GetType().GetProperties().Where(prop => prop.PropertyType == typeof(AnalyzedParameter<>));
        var valid = props.All(p => ((AnalyzedParameter<object>) p.GetValue(this)).Valid);

        return valid;
    }

But it does not work. Any ideas?





Aucun commentaire:

Enregistrer un commentaire