aboutsummaryrefslogtreecommitdiff
path: root/csharp/src/ProtocolBuffers/FieldAccess/FieldAccessorBase.cs
blob: 51b9493180b519bc1c745e6a3a8834c6dd1c0dc2 (plain) (blame)
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Google.Protobuf;
using Google.Protobuf.FieldAccess;

namespace Google.Protobuf.FieldAccess
{
    /// <summary>
    /// Base class for field accessors.
    /// </summary>
    /// <typeparam name="T">Type of message containing the field</typeparam>
    internal abstract class FieldAccessorBase<T> : IFieldAccessor<T> where T : IMessage<T>
    {
        private readonly Func<T, object> getValueDelegate;

        internal FieldAccessorBase(string name)
        {
            PropertyInfo property = typeof(T).GetProperty(name);
            if (property == null || !property.CanRead)
            {
                throw new ArgumentException("Not all required properties/methods available");
            }
            getValueDelegate = ReflectionUtil.CreateUpcastDelegate<T>(property.GetGetMethod());
        }

        public object GetValue(T message)
        {
            return getValueDelegate(message);
        }

        public abstract bool HasValue(T message);
        public abstract void Clear(T message);
        public abstract void SetValue(T message, object value);
    }
}