gpt4 book ai didi

c# - 如何返回属性的默认值?

转载 作者:太空宇宙 更新时间:2023-11-03 18:52:52 25 4
gpt4 key购买 nike

我有以下 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# 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 属性的默认值设置为今天的日期,如您所愿。

关于c# - 如何返回属性的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53157034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com