How to pass arguments to a non-default constructor?

前端 未结 3 1468
悲&欢浪女
悲&欢浪女 2020-12-06 00:18

I have approximately the following picture:

public class Foo
{
   public Foo(Bar bar, String x, String y)
   {
       this.Bar = bar;
       this.X = x;
             


        
3条回答
  •  醉话见心
    2020-12-06 00:45

    I'm not an expert on Json.NET, but AFAIK that simply is not possible. If I were you, I would look at options to fixup this after deserialization.

    Very few serialization APIs will allow you to control construction to that degree; the four most typical approaches are (most common first):

    • invoke the parameterless constructor
    • skip the constructor completely
    • use a constructor that has an obvious 1:1 mapping to the members being serialized
    • use a user-supplied factory method

    It sounds like you want the last, which is pretty rare. You may have to settle for doing this outside the constructor.

    Some serialization APIs offer "serialization/deserialization callbacks", which allow you to run a method on the object at various points (typically before and after both serialize and deserialize), including passing some context information into the callback. IF Json.NET supports deserialization callbacks, that might be the thing to look at. This question suggests that the [OnDeserialized] callback pattern may indeed be supported; the context comes from the JsonSerializerSettings's .Context property that you can optionally supply to the deserialize method.

    Otherwise, just run it manually after deserialization.

    My rough pseudo-code (completely untested):

    // inside type: Foo
    [OnDeserialized]
    public void OnDeserialized(StreamingContext ctx) {
        if(ctx != null) {
            Bar bar = ctx.Context as Bar;
            if(bar != null) this.Bar = bar; 
        }
    }
    

    and

    var ctx = new StreamingContext(StreamingContextStates.Other, bar);
    var settings = new JsonSerializerSettings { Context = ctx };
    var obj = JsonConvert.DeserializeObject(fooJsonString, settings);
    

提交回复
热议问题