How to deserialize class without calling a constructor?

后端 未结 4 874
长发绾君心
长发绾君心 2021-01-01 16:38

I\'m using Json.NET in my WCF data service.

Here\'s my class (simplified):

[DataContract]
public class Component
{
    public Component()
    {
              


        
4条回答
  •  感动是毒
    2021-01-01 16:52

    A constructor is always invoked. I usually have two constructors. One for serialization (the default constructor) and one for all "regular" code:

    [DataContract]
    public class Component
    {
        // for JSON.NET
        protected Component()
        {
        }
    
        public Component(allMandatoryFieldsHere)
        {
            // I'm doing some magic here.
        }
    }
    

    In that way I can also make sure that the dev specify all information which are required.

    However, I do not really recommend that you use anything but DTO's when transfering information since it's otherwise possible to circumvent the encapsulation of your objects (anyone could initialize any field with any value). Well. If you use anything but anemic models.

    Using FormatterServices.GetSafeUninitializedObject is imho therefore an ugly workaround, since no one can tell that you create all objects in an unintialized way. Constructor initialization is there for a reason. It's better that the classes can tell that it's OK to not call the real constructor by providing a "serialization" constructor as I suggested.

提交回复
热议问题