简体   繁体   English

c#没有为DTO属性中的类型定义无参数构造函数

[英]c# no parameterless constructor defined for type in DTO property

I have a question I have a simple operation that is using RestClient to get info, and code looks like:我有一个问题,我有一个使用 RestClient 获取信息的简单操作,代码如下所示:

 var client = new RestClient(RestClientBaseUrl);
 IRestResponse request = client.Execute(new RestRequest("Application/GetApplications", Method.GET));
 IEnumerable<DTO.Application> response = new JsonDeserializer().Deserialize<IEnumerable<DTO.Application>>(request);

DTO for this model looks like:此模型的 DTO 如下所示:

public class Application
{
    public int? Id { get; set; }
    public string Name { get; set; }
    public GetSystem[] Systems { get; set; }
}

and for system it looks like:对于系统,它看起来像:

public class GetSystem : SystemTemplate
{
    public int Id { get; set; }
    public SystemState SystemState { get; set; }
}

System template系统模板

public abstract class SystemTemplate
{
    public string Name { get; set; }
    public string IpAddress { get; set; }
    public int Port { get; set; }
}

and SystemState:和系统状态:

public class SystemState
{
    public int? Id { get; set; }
    public byte MaintenanceMode { get; set; }
    public string LastCommunicationTimestamp { get; set; }
    public int SystemId { get; set; }
}

Now problem is when I deserialize Json I am getting:现在的问题是当我反序列化 Json 时,我得到:

System.MissingMethodException : No parameterless constructor defined for type 'DS.Models.DTO.GetSystem[]'.

What could be the problem?可能是什么问题呢?

您需要在 GetSystem 类中添加一个空的构造函数。

During deserialization JsonDeserializer needs to create the object first and then populates it with data.在反序列化期间 JsonDeserializer 需要先创建对象,然后用数据填充它。 It will use the default parameterless contrusctor for that.它将为此使用默认的无参数构造函数。 It obviously cannot create the object.它显然不能创建对象。 Check, that you can actually create your object, ie:检查,您实际上可以创建您的对象,即:

GetSystem getSystem = new GetSystem();

The GetSystem seems to be ok, so the problem must be in the base class SystemTemplate or some other base class you didn't post. GetSystem 似乎没问题,所以问题一定出在基类 SystemTemplate 或您没有发布的其他一些基类中。 You will need to add the parameterless constructor and make it accessible to the calling class.您将需要添加无参数构造函数并使其可供调用类访问。 Make sure it is not private.确保它不是私人的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM