mercredi 20 avril 2022

C# Reflection get the instance behind FieldInfo

I am having an issue with Reflection, which I can't seem to find a solution for.

I have the following simple interface :

    public interface IDataProperty<T> 
{
   public T Value { get; set; } 
   public int BytesCount();
   public byte[] Serialize();
}

the struct which implements the interface above :

    public struct IntProperty : IDataPropery<int> 
{
    private int _value; 
    public int Value { get => _value; set => _value = value; }

    public int BytesCount()
    {
        return 4;
    }

    public byte[] Serialize()
    {
        return BitConverter.GetBytes(_value);
    }
    public IntDataProperty(int value) { _value = value; }
}

and a simple class to hold the values :

public class ValuesContainer  
{
   public IntProperty prop1;
   public IntProperty prop2;
}

I am trying to call the Serialize() method on both prop1 and prop2 in my Processor class, with no luck so far... :

public class Processor  
{
   public void ProccesData<T>(out T result) where T : ValuesContainer, new() 
    {
      result = new T();
        List<FieldInfo> dataFields = new List<FieldInfo>();
        result.GetType().GetFields().ToList().ForEach(field => { 
        if(field.FieldType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDataProperty<>)))
            {
                dataFields.Add(field);
            }
              });
         MethodInfo serializeMI = typeof(IDataProperty<>).GetMethod("Serialize");
         foreach(FieldInfo field in dataFields)
        {
            Console.WriteLine(field.Name);
            serializeMI.Invoke(field,null);
        }

    }
}

Running the code at this point gives me the following error :

'Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.'

I am aware that I need to get somehow to the instance behind the field variable, but have no idea how to do it. Does anyone know a good way of doing what i am trying to achieve using other methods, or only Reflection is the way to go, and if the latter - what solutions do I have ?

Thanks in advance to all of you.





Aucun commentaire:

Enregistrer un commentaire