lundi 16 septembre 2019

Dynamically casting in C# recursively with Reflection

I've searched this issue on the internet, I found some ways but they didn't suitable for my problem. This is my code and I need to cast fields in my class that is the type of some another class.

    public void CheckObjectFormatValues(object o)
    {
        FieldInfo[] fields = o.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (System.Reflection.FieldInfo prp in fields)
        {

            if (prp.FieldType.BaseType != typeof(ValueType))
            {
                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ArrivalType")
                    CheckObjectFormatValues((ArrivalType)prp.GetValue(o));

                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.Cell")
                    CheckObjectFormatValues((Cell)prp.GetValue(o));

                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ObjectType")
                    CheckObjectFormatValues((ObjectType)prp.GetValue(o));

                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ObjAction")
                    CheckObjectFormatValues((ObjAction)prp.GetValue(o));
            }
            else
            {
                var value = prp.GetValue(o).ToString();
                if (value == "-1")
                    throw new Exception("Error");
            }
        }
    }

Is there any way to refactor my If block with recursive function and cast dynamically?





Aucun commentaire:

Enregistrer un commentaire