How to pass arguments to a non-default constructor?

前端 未结 3 1466
悲&欢浪女
悲&欢浪女 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 01:01

    If you have a constructor whose only parameters are your non-serialized values, create your instance first and then populate your object instead of deserializing. The JsonConvert class has a PopulateObject method, defined as follows:

    public static void PopulateObject(
        string value,                      // JSON string
        object target)                     // already-created instance
    

    If you have particular serialization settings, there's an overload that also includes a JsonSerializerSettings parameter.

    Add a Foo constructor that has a single Bar parameter, you could do something like:

    var bar = new Bar("Hello World");
    var foo = new Foo(bar);
    JsonConvert.PopulateObject(fooJsonString, foo);
    

    You may need to adjust your class to use fields for mapping, or make adjustments to NHibernate to allow writing to private setters (use of a custom IProxyValidator class).

提交回复
热议问题