<small id='TbcCF'></small><noframes id='TbcCF'>

    1. <i id='TbcCF'><tr id='TbcCF'><dt id='TbcCF'><q id='TbcCF'><span id='TbcCF'><b id='TbcCF'><form id='TbcCF'><ins id='TbcCF'></ins><ul id='TbcCF'></ul><sub id='TbcCF'></sub></form><legend id='TbcCF'></legend><bdo id='TbcCF'><pre id='TbcCF'><center id='TbcCF'></center></pre></bdo></b><th id='TbcCF'></th></span></q></dt></tr></i><div id='TbcCF'><tfoot id='TbcCF'></tfoot><dl id='TbcCF'><fieldset id='TbcCF'></fieldset></dl></div>
        <bdo id='TbcCF'></bdo><ul id='TbcCF'></ul>

      <legend id='TbcCF'><style id='TbcCF'><dir id='TbcCF'><q id='TbcCF'></q></dir></style></legend>

        <tfoot id='TbcCF'></tfoot>

      1. 如何将参数传递给非默认构造函数?

        时间:2023-08-23
      2. <small id='dZOhp'></small><noframes id='dZOhp'>

      3. <legend id='dZOhp'><style id='dZOhp'><dir id='dZOhp'><q id='dZOhp'></q></dir></style></legend>

          <tbody id='dZOhp'></tbody>
          <bdo id='dZOhp'></bdo><ul id='dZOhp'></ul>
          <tfoot id='dZOhp'></tfoot>

                • <i id='dZOhp'><tr id='dZOhp'><dt id='dZOhp'><q id='dZOhp'><span id='dZOhp'><b id='dZOhp'><form id='dZOhp'><ins id='dZOhp'></ins><ul id='dZOhp'></ul><sub id='dZOhp'></sub></form><legend id='dZOhp'></legend><bdo id='dZOhp'><pre id='dZOhp'><center id='dZOhp'></center></pre></bdo></b><th id='dZOhp'></th></span></q></dt></tr></i><div id='dZOhp'><tfoot id='dZOhp'></tfoot><dl id='dZOhp'><fieldset id='dZOhp'></fieldset></dl></div>
                  本文介绍了如何将参数传递给非默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

                  问题描述

                  我大概有以下图片:

                  public class Foo
                  {
                     public Foo(Bar bar, String x, String y)
                     {
                         this.Bar = bar;
                         this.X = x;
                         this.Y = y;
                     }
                  
                     [JsonIgnore]
                     public Bar Bar { get; private set; }
                  
                     public String X { get; private set; }
                     public String Y { get; private set; }
                  }
                  
                  public class Bar
                  {
                      public Bar(String z)
                      {
                          this.Z = z;
                      }
                  
                      public String Z { get; private set; }
                  }
                  

                  我想在反序列化期间以某种方式将 Bar 类型的对象传递给 Foo 类型的构造函数,即:

                  I want somehow to pass an object of type Bar to a constructor of type Foo during deserialization, i.e:

                  var bar = new Bar("Hello world");
                  var x = JsonConvert.DeserializeObject<Foo>(fooJsonString, bar);
                  

                  推荐答案

                  以下是我对解决问题的想法:

                  Here are my thoughts regarding problem solution:

                  Json.Net 的自定义反序列化 api 不透明,即影响我的类层次结构.

                  Json.Net's custom deserialization api is not transparent, i.e. affects my class hierarchy.

                  实际上,如果您的项目中有 10-20 个类,这不是问题,但如果您有包含数千个类的大型项目,您对需要使用 Json 遵守 OOP 设计这一事实并不特别高兴.净需求.

                  Actually it's not a problem in case when you have 10-20 classes in your project, though if you have huge project with thousands of classes, you are not particularly happy about the fact that you need comply your OOP design with Json.Net requirements.

                  Json.Net 非常适合在创建后填充(初始化)的 POCO 对象.但这并非在所有情况下都是正确的,有时您会在构造函数中初始化对象.为了使初始化发生,您需要传递正确"的参数.这些正确"的参数可以在序列化文本中,也可以在一段时间之前已经创建和初始化.不幸的是,Json.Net 在反序列化期间将默认值传递给他不理解的参数,在我的情况下,它总是导致 ArgumentNullException.

                  Json.Net is good with POCO objects which are populated (initialized) after they are created. But it's not truth in all cases, sometimes you get your objects initialized inside constructor. And to make that initialization happen you need to pass 'correct' arguments. These 'correct' arguments can either be inside serialized text or they can be already created and initialized some time before. Unfortunately Json.Net during deserialization passes default values to arguments that he doesn't understand, and in my case it always causes ArgumentNullException.

                  这是一种允许在反序列化期间使用任何序列化或非序列化参数集创建真正的自定义对象的方法,主要问题是该方法不是最佳的,它需要每个需要自定义反序列化的对象的 2 个反序列化阶段,但它可以工作并允许以您需要的方式反序列化对象,所以这里是:

                  Here is approach that allows real custom object creation during deserialization using any set of arguments either serialized or non-serialized, the main problem is that the approach sub-optimal, it requires 2 phases of deserialization per object that requires custom deserialization, but it works and allows deserializing objects the way you need it, so here goes:

                  首先我们按照以下方式重新组装 CustomCreationConverter 类:

                  First we reassemble the CustomCreationConverter class the following way:

                  public class FactoryConverter<T> : Newtonsoft.Json.JsonConverter
                  {
                      /// <summary>
                      /// Writes the JSON representation of the object.
                      /// </summary>
                      /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
                      /// <param name="value">The value.</param>
                      /// <param name="serializer">The calling serializer.</param>
                      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
                      {
                          throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
                      }
                  
                      /// <summary>
                      /// Reads the JSON representation of the object.
                      /// </summary>
                      /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
                      /// <param name="objectType">Type of the object.</param>
                      /// <param name="existingValue">The existing value of object being read.</param>
                      /// <param name="serializer">The calling serializer.</param>
                      /// <returns>The object value.</returns>
                      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
                      {
                          if (reader.TokenType == JsonToken.Null)
                              return null;
                  
                          T value = CreateAndPopulate(objectType, serializer.Deserialize<Dictionary<String, String>>(reader));
                  
                          if (value == null)
                              throw new JsonSerializationException("No object created.");
                  
                          return value;
                      }
                  
                      /// <summary>
                      /// Creates an object which will then be populated by the serializer.
                      /// </summary>
                      /// <param name="objectType">Type of the object.</param>
                      /// <returns></returns>
                      public abstract T CreateAndPopulate(Type objectType, Dictionary<String, String> jsonFields);
                  
                      /// <summary>
                      /// Determines whether this instance can convert the specified object type.
                      /// </summary>
                      /// <param name="objectType">Type of the object.</param>
                      /// <returns>
                      ///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
                      /// </returns>
                      public override bool CanConvert(Type objectType)
                      {
                          return typeof(T).IsAssignableFrom(objectType);
                      }
                  
                      /// <summary>
                      /// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
                      /// </summary>
                      /// <value>
                      ///     <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
                      /// </value>
                      public override bool CanWrite
                      {
                          get
                          {
                              return false;
                          }
                      }
                  }
                  

                  接下来我们创建将创建我们的 Foo 的工厂类:

                  Next we create the factory class that will create our Foo:

                  public class FooFactory : FactoryConverter<Foo>
                  {
                      public FooFactory(Bar bar)
                      {
                          this.Bar = bar;
                      }
                  
                      public Bar Bar { get; private set; }
                  
                      public override Foo Create(Type objectType, Dictionary<string, string> arguments)
                      {
                          return new Foo(Bar, arguments["X"], arguments["Y"]);
                      }
                  }
                  

                  这里是示例代码:

                  var bar = new Bar("BarObject");
                  
                  var fooSrc = new Foo
                  (
                      bar,
                      "A", "B"
                  );
                  
                  var str = JsonConvert.SerializeObject(fooSrc);
                  
                  var foo = JsonConvert.DeserializeObject<Foo>(str, new FooFactory(bar));
                  
                  Console.WriteLine(str);
                  

                  在这种情况下 foo 包含一个我们需要在反序列化期间传递给 Foo 构造函数的参数.

                  In this case foo contains an argument that we needed to pass to a Foo constructor during deserialization.

                  这篇关于如何将参数传递给非默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                  上一篇:使用 Json.NET 反序列化键值对数组 下一篇:自定义反序列化器仅适用于带有 json.NET 的某些字

                  相关文章

                  最新文章

                    • <bdo id='ZNEti'></bdo><ul id='ZNEti'></ul>

                    <i id='ZNEti'><tr id='ZNEti'><dt id='ZNEti'><q id='ZNEti'><span id='ZNEti'><b id='ZNEti'><form id='ZNEti'><ins id='ZNEti'></ins><ul id='ZNEti'></ul><sub id='ZNEti'></sub></form><legend id='ZNEti'></legend><bdo id='ZNEti'><pre id='ZNEti'><center id='ZNEti'></center></pre></bdo></b><th id='ZNEti'></th></span></q></dt></tr></i><div id='ZNEti'><tfoot id='ZNEti'></tfoot><dl id='ZNEti'><fieldset id='ZNEti'></fieldset></dl></div>
                    <tfoot id='ZNEti'></tfoot><legend id='ZNEti'><style id='ZNEti'><dir id='ZNEti'><q id='ZNEti'></q></dir></style></legend>
                    1. <small id='ZNEti'></small><noframes id='ZNEti'>