lundi 10 septembre 2018

When using reflection, why aren't values being set correctly?

I'm trying to use reflection to create a struct.

First, here is the method that isn't working correctly:

    public TFilter GetFilter<TFilter>() where TFilter : struct
    {
        // Get the filter type and all of it's fields.
        var filterType = typeof(TFilter);
        var filterFields = filterType.GetFields();

        // Create an instance of the filter type.
        var result = Activator.CreateInstance<TFilter>();

        // Loop through all it's fields
        foreach (var filterField in filterFields)
        {
            // Get the struct from the fields type.
            var someStruct = this.someInterfaces.First(s => s.GetType() == filterField.FieldType);

            // Finally, lets set the value to the correct component.
            filterField.SetValue(result, someStruct);
        }

        return result;
    }

For some reason, if I use this method like in the following example, the set values are incorrect:

    public struct SomeStruct : ISomeInterface
    {
        public float SomeFloat;

        public SomeStruct(float someFloat)
        {
            this.SomeFloat = someFloat;
        }
    }

    public struct Filter
    {
        public SomeStruct SomeStruct;
    }

    private static void Main(string[] args)
    {
        var someStruct = new SomeStruct(10.0f);

        var someClass = new SomeClass();
        someClass.Add(someStruct);

        var filter = someClass.GetFilter<Filter>();

        // Should print 10.0f, prints 0.
        Console.WriteLine(filter.SomeStruct.SomeFloat);
        Console.ReadLine();
    }

I'm not sure why this isn't working and I'm just looking for a bit of help :)





Aucun commentaire:

Enregistrer un commentaire