[英]Is there any way I can bring properties into a Class without using Inheritance?
[英]Is there a way to ignore class properties without using annotations
以下是返回Agent對象的api調用
[Route("GetAgentById")]
public Agent GetAgentById(int id)
{
//Restrict Class fields
return new Agent(id);
}
代理類有很多字段(假設100個字段)
public class Agent
{
public int AgentId { get; set; }
public string AgentName { get; set; }
public bool IsAssigned { get; set; }
public bool IsLoggedIn { get; set; }
......
......
public Agent() { }
}
有沒有一種方法可以忽略類屬性而不使用注釋。 我只想在從api調用返回代理對象之前返回代理對象的某些字段。 有什么辦法做到這一點
返回僅具有必需屬性的匿名對象,例如:
return new { agent.AgentId, agent.AgentName }
或使用DTO(在結構上會更正確,特別是在構建復雜的解決方案時),在此示例中使用Automapper :
return Mapper.Map<AgentDTO>(agent);
但是,如果您真的想使用“選擇退出”方法並僅序列化對象的一小部分,並且使用的是JSON.NET,則可以僅標記需要序列化的屬性:
[DataContract]
public class Agent
{
// included in JSON
[DataMember]
public int AgentId { get; set; }
[DataMember]
public string AgentName { get; set; }
// ignored
public bool IsAssigned { get; set; }
public bool IsLoggedIn { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.