如何返回属性的默认值?

san*_*tro 1 .net c# properties default-value

我有以下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; }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决这个问题吗?

Sal*_*ari 6

如果您使用的是C#6+,它已添加了为自动属性分配默认值的功能.所以你可以简单地写下这样的东西:

public string Name { get; set; } = "No Name";
public DateTime Created { get; private set; } = DateTime.Today;
Run Code Online (Sandbox Code Playgroud)

这将根据需要将Name属性的默认值No Name和Created属性设置为今天的日期.