示例#1
0
        /// <summary>
        /// Reads a <see cref="IPoco"/> (that can be null) from the Json reader
        /// that must have been written with its type.
        /// </summary>
        /// <param name="this">This directory.</param>
        /// <param name="reader">The Json reader.</param>
        /// <param name="options">The options.</param>
        /// <returns>The Poco (can be null).</returns>
        public static IPoco?Read(this PocoDirectory @this, ref Utf8JsonReader reader, PocoJsonSerializerOptions?options = null)
        {
            if (@this == null)
            {
                throw new ArgumentNullException(nameof(@this));
            }
            if (CheckNullStart(ref reader, "expecting Json Poco array or null value."))
            {
                return(null);
            }

            if (reader.TokenType != JsonTokenType.StartArray)
            {
                throw new JsonException("Expecting Json Poco array.");
            }
            reader.Read();
            string?      name = reader.GetString();
            IPocoFactory?f    = name != null? @this.Find(name) : null;

            if (f == null)
            {
                throw new JsonException($"Poco type '{name}' not found.");
            }
            reader.Read();
            var p = ((IFactoryReader)f).ReadTyped(ref reader, options);

            if (reader.TokenType != JsonTokenType.EndArray)
            {
                throw new JsonException("Expecting Json Poco end array.");
            }
            reader.Read();
            return(p);
        }
        /// <summary>
        /// Creates a new <see cref="IPoco"/> instance.
        /// </summary>
        /// <typeparam name="T">The type of the poco.</typeparam>
        /// <param name="this">This directory.</param>
        /// <returns>A new instance.</returns>
        public static T Create <T>(this PocoDirectory @this) where T : IPoco
        {
            var c = @this.Find(typeof(T));

            if (c == null)
            {
                Throw.Exception($"Unable to resolve IPoco interface '{typeof(T)}' from PocoDirectory.");
            }
            return((T)c.Create());
        }