vendredi 1 février 2019

How to Initialize Structure as Generic Type using Reflection

In my application there is a structure MY_STRUCT and three classes: MyContainerClass<T>, MyBaseClass<T>, and MyDerivedClass. How do I initialize MY_STRUCT using reflection where MY_STRUCT is generic type T in the base and container classes?

struct MY_STRUCT
{
    public float[] prop1;
    public float[] prop2;
    public float prop3;
    public uint prop4;
    public ushort prop5;
};

class MyDerivedClass : MyBaseClass<MY_STRUCT>
{
    private List<PropertyInfo> _propertyInfo = new List<PropertyInfo>
    {
        typeof(float[]).GetProperty("prop1"),
        typeof(float[]).GetProperty("prop2"),
        typeof(float).GetProperty("prop3"),
        typeof(uint).GetProperty("prop4"),
        typeof(ushort).GetProperty("prop5"),
    };

    public MyDerivedClass() : base(this._propertyInfo)
    {
        MyContainerClass<MY_STRUCT>.Presented = new MyContainerClass<MY_STRUCT>();
    }
}

class MyBaseClass<T>
{
    // Not sure whether to use this, or pass List<PropertyInfo> as some
    //   structure elements are arrays with differing lengths.
    public MyBaseClass(List<KeyValuePair<string, object>> fieldDataList) : base()
    {
        foreach (KeyValuePair<string, object> fieldData in fieldDataList)
        {
            if (false != this._calData.GetType().GetProperty(fieldData.Key).PropertyType.IsArray)
            {
                object[] arrayInfo = (object[])fieldData.Value;
                Type type = (Type)arrayInfo[0];
                int length = (int)arrayInfo[1];
                object value = null;

                if (typeof(float).Equals(type))
                {
                    value = new float[length];
                }
                else if (typeof(uint).Equals(type))
                {
                    value = new uint[length];
                }
                else if (typeof(ushort).Equals(type))
                {
                    value = new ushort[length];
                }
                else if (typeof(byte).Equals(type))
                {
                    value = new byte[length];
                }
                else
                {
                    throw new NotImplementedException();
                }

                this.SetValue(fieldData.Key, value);
            }
        }
    }
}

class MyContainerClass<T>
{
    public static MyBaseClass<T> Presented = null;
    public static MyBaseClass<T> Responded = null;

    public Calibration() {}
}

I'm new to reflection, and I know there are probably multiple problems with my posted implementation. Any help would be great.





Aucun commentaire:

Enregistrer un commentaire