-->

A question about remove the get and set value in d

2019-08-04 07:03发布

问题:

As now I have started to use Script#, I tried to send a data package to server via ajax:

jQuery.AjaxRequest<RespondPackage>(url, new jQueryAjaxOptions("type", "POST", "dataType", "json", "data",  dataSendToServer));

with dataSendToServer is in form of object Type "SendPackage" using get and set accessor, like this:

public class SendPackage
{  private string reportID;
    public string ReportID
    {
        get { return reportID; }
        set { reportID = value; }
    }
    public SendPackage(string reportID)
    {
        this.reportID = reportID;
    }
}

While sending the data to server using ajax after transform to Javascript, it send not only the reportID (the data needed) , but also get_reportID and set_reportID.

I have tried several method to remove the dummy properties of the get and set accessor like Type.DeleteField but it seems doesn't work. Therefore I want to ask if there is any method to treat the data sending to server to remove the property of get and set accessor?

Thanks for your attention.

回答1:

Use a record class, i.e. derive your class from the Record base class.

Record classes don't get defined as a regular class - instead only a factory method representing your ctor is created. The result of the factory is a vanilla object which serializes into a JSON object as you'd expect.

Record classes cannot have methods or properties - just public properties and at most a ctor.

Note that you could also have any class implement a ToJSON method - that gets to override what gets serialized when using the JSON functionality built into the script engine (and presumably jQuery also uses it).



回答2:

Why about just make the class as:

public class SendPackage
{  
    public string reportID;

    public SendPackage(string reportID)
    {
        this.reportID = reportID;
    }
}

i.e make the field public and get rid of the property.