예제 #1
0
        private T Cast(object item)
        {
            var isResource = Resource.ResourceTypeInfo.IsAssignableFrom(_targetTypeInfo);

            if (isResource)
            {
                var nestedData = item as IDictionary <string, object>;
                return(_resourceFactory.CreateFromExistingData <T>(nestedData));
            }

            var isStringEnum = StringEnum.TypeInfo.IsAssignableFrom(_targetTypeInfo);

            if (isStringEnum)
            {
                return(StringEnum.Create <T>(item?.ToString()));
            }

            // Fall back to primitive conversion
            try
            {
                return((T)Convert.ChangeType(item, typeof(T)));
            }
            catch (InvalidCastException ice)
            {
                _logger.LogWarning($"Tried to access type '{item.GetType().Name}' in an array of type '{typeof(T).Name}'; returning default value. Value: '{item}'. Exception: {ice.Message}");
                return(default(T));
            }
        }