dimanche 29 décembre 2019

Determine if object has field of passed type with specific child value [duplicate]

This question already has an answer here:

I would like to know if it is possible to determine if an object has Fields with specific types (which I believe can be done with reflection using GetField(name)), and also to then determine if that field has a specific value.

For example, suppose we have the following:

public class Foo
{
    public string Value;
}

public class Bar
{
    public string Value;
}

public class Abc
{
    public Foo Foo;
    public Bar Bar;
}

I would like to be able to be able to do the following:

public static class FieldChecker
{
    public static bool HasDesiredValue(Abc abcObject, Type fieldType, string value)
    {
        FieldInfo info = abcObject.GetType().GetField(fieldType.Name); //See notes below on why this is ok

        if (info != null && info.FieldType == fieldType)
        {
            //Here is my issue. This obviously isn't real code. Can something like this be done?
            if (abcObject.[FieldWithPassedInTypeAndName].Value == value)
            {
                return true;
            }
        }

        return false;
    }
}

Used like this:

Abc abcObject = new Abc()
{
    Foo = new Foo()
    {
        Value = "SomeValue"
    }
};

bool boolOne = FieldChecker.HasDesiredValue(abcObject, typeof(Foo), "SomeValue"); //true
bool boolTwo = FieldChecker.HasDesiredValue(abcObject, typeof(Foo), "SomeOtherValue"); //false

Notes:

  • The field name and the field type will always be the same, which is why I can use GetField(fieldType.Name). If there is a better way to do this I welcome feedback.
  • The thing I'm interested in checking will always be called Value, and will always be a field on the field of the passed in type, so if there is a way to get the field, then [whatever].Value is what I'm interested in checking, nomatter what field type I pass in.
  • There will only ever be 1 field with the desired type (i.e. there will never be 2 Foo fields in the Abc class, and even if there were I'm only interested in the field named Foo)
  • In the real world, the Abc object is being generated using deserialization. I'm not initializing it in code.
  • The Abc class was/is generated by a tool, so it cannot (shouldn't) be edited, so I can't make this a method in the Abc class. Also I'm interested in checking a lot of different values (in the real world the Abc class has tens of fields that I'm interested in checking) so a generic method would be the easiest I'm assuming.




Aucun commentaire:

Enregistrer un commentaire