【问题标题】:How to return a default value for a property?如何返回属性的默认值?
【发布时间】:2019-04-08 23:14:41
【问题描述】:

我有以下 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; }
}

谁能帮我解决这个问题?

【问题讨论】:

    标签: c# .net properties default-value


    【解决方案1】:

    如果您使用的是 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 属性的默认值设置为今天的日期,如您所愿。

    【讨论】:

    • 非常感谢您的快速回复。它对我有用:)
    猜你喜欢
    • 2013-02-02
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2012-05-28
    • 2020-06-11
    • 2021-11-18
    相关资源
    最近更新 更多