代码之家  ›  专栏  ›  技术社区  ›  santosh kumar patro

如何返回属性的默认值?

  •  1
  • santosh kumar patro  · 技术社区  · 6 年前

    我有以下Graphql类型类,包括POCO类: Order.cs .

    这里我想设置每个字段的默认值。例如 Name 我想返回“No Name”,以防没有返回值。万一 Created

    public class OrderType : ObjectGraphType<Order>
    {
        public OrderType(ICustomerService customers)
        {
            Field(o => o.Id);
            Field(o => o.Name);
            Field(o => o.Description);
            Field(o => o.Created);
        }
    }
    
    public class Order
    {
        public Order(string name, string description, DateTime created, string Id)
        {
            Name = name;
            Description = description;
            Created = created;
            this.Id = Id;
        }
    
        public string Name { get; set; }
    
        public string Description { get; set; }
    
        public DateTime Created { get; private set; }
    
        public string Id { get; private set; }
    }
    

    有人能帮我解决这个问题吗?

    1 回复  |  直到 6 年前
        1
  •  8
  •   Salah Akbari    6 年前

    如果您使用的是C#6+,它会添加 the ability to assign a default value to auto-properties . 所以你可以这样写:

    public string Name { get; set; } = "No Name";
    public DateTime Created { get; private set; } = DateTime.Today;
    

    这将设置 Name 属性到 No Name Created