Ejemplo n.º 1
0
        /// <summary>
        /// Retrieves a value
        /// </summary>
        /// <param name="target">The object to retrieve the value from</param>
        /// <param name="propertyName">The name of the property to get the value from</param>
        /// <returns>The value of the property</returns>
        public object GetValue(object target, string propertyName)
        {
            if (propertyName.Contains(".")) // Support nested properties
            {
                var propertyNames = propertyName.Split('.');

                var typeAccessor = this; // The type accessor needs to change for each new target

                PropertyAccessor propertyAccessor = null;

                foreach (var name in propertyNames)
                {
                    if (!typeAccessor.PropertyAccessors.ContainsKey(name))
                    {
                        throw new InvalidOperationException($"Property: '{name}' not found for object of type: '{target.GetType().FullName}'");
                    }

                    propertyAccessor = typeAccessor.PropertyAccessors[name];

                    if (!propertyAccessor.CanGet)
                    {
                        throw new InvalidOperationException($"Can not get the value of property: '{propertyAccessor.PropertyName}'");
                    }

                    if (name != propertyNames.Last()) // Assume the last property as a scalar (primitive) value
                    {
                        var t = propertyAccessor.GetValue(target);

                        if (t == null) // Nested property instance does not exist
                        {
                            return(null);
                        }

                        target = t;

                        typeAccessor = t.GetTypeAccessor();
                    }
                }

                return(propertyAccessor.GetValue(target));
            }
            else
            {
                if (!PropertyAccessors.ContainsKey(propertyName))
                {
                    throw new InvalidOperationException($"Property: '{propertyName}' not found for object of type: '{target.GetType().FullName}'");
                }

                PropertyAccessor propertyAccessor = PropertyAccessors[propertyName];

                if (!propertyAccessor.CanGet)
                {
                    throw new InvalidOperationException($"Can not get the value of property: '{propertyAccessor.PropertyName}'");
                }

                return(propertyAccessor.GetValue(target));
            }
        }
Ejemplo n.º 2
0
 public object GetValue()
 {
     return(_accessor.GetValue(_object));
 }