summaryrefslogtreecommitdiff
path: root/Plugins/MonoGame.Extended/source/MonoGame.Extended.Tweening/TweenFieldMember.cs
blob: da2f75d450d6970f56b0c584a4db1c1105d46024 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;

namespace MonoGame.Extended.Tweening
{
    public sealed class TweenFieldMember<T> : TweenMember<T>
        where T : struct 
    {
        private readonly FieldInfo _fieldInfo;

        public TweenFieldMember(object target, FieldInfo fieldInfo) 
            : base(target, CompileGetMethod(fieldInfo), CompileSetMethod(fieldInfo))
        {
            _fieldInfo = fieldInfo;
        }

        private static Func<object, object> CompileGetMethod(FieldInfo fieldInfo)
        {
            var self = Expression.Parameter(typeof(object));
            var instance = Expression.Convert(self, fieldInfo.DeclaringType);
            var field = Expression.Field(instance, fieldInfo);
            var convert = Expression.TypeAs(field, typeof(object));

            return Expression.Lambda<Func<object, object>>(convert, self).Compile();
        }

        private static Action<object, object> CompileSetMethod(FieldInfo fieldInfo)
        {
            Debug.Assert(fieldInfo.DeclaringType != null);

            var self = Expression.Parameter(typeof(object));
            var value = Expression.Parameter(typeof(object));
            var fieldExp = Expression.Field(Expression.Convert(self, fieldInfo.DeclaringType), fieldInfo);
            var assignExp = Expression.Assign(fieldExp, Expression.Convert(value, fieldInfo.FieldType));

            return Expression.Lambda<Action<object, object>>(assignExp, self, value).Compile();
        }

        public override Type Type => _fieldInfo.FieldType;
        public override string Name => _fieldInfo.Name;
    }
}