internal static OpenType FromType()

in src/Microsoft.Azure.WebJobs.Host/Bindings/OpenType.cs [96:151]


        internal static OpenType FromType(Type t)
        {
            if (t == typeof(OpenType) || t == typeof(object))
            {
                return new AnythingOpenType();
            }
            if (typeof(OpenType).IsAssignableFrom(t))
            {
                return (OpenType)Activator.CreateInstance(t);
            }

            if (t.IsArray)
            {
                var elementType = t.GetElementType();
                var innerType = FromType(elementType);
                if (innerType is ExactMatch)
                {
                    return new ExactMatch(t);
                }
                return new ArrayOpenType(innerType);
            }

            // Rewriter rule for generics so customers can say: IEnumerable<OpenType> 
            if (t.IsGenericType)
            {
                var outerType = t.GetGenericTypeDefinition();
                Type[] args = t.GetGenericArguments();
                if (args.Length == 1)
                {
                    var arg1 = FromType(args[0]);
                    if (arg1 is ExactMatch)
                    {
                        return new ExactMatch(t);
                    }
                    else 
                    {
                        return new SingleGenericArgOpenType(outerType, arg1);
                    }
                    // This is a concrete generic type, like IEnumerable<JObject>. No open types needed. 
                }
                else
                {
                    // Just to sanity check, make sure there's no OpenType buried in the argument. 
                    // This could be nested. IFoo<int, IBar<OpenType>>
                    foreach (var arg in args)
                    {
                        if (FromType(arg).GetType() != typeof(ExactMatch))
                        {
                            throw new NotSupportedException("Embedded Open Types are only supported for types with a single generic argument.");
                        }
                    }
                }
            }

            return new ExactMatch(t);
        }